ElCapitaine ElCapitaine - 1 year ago 111
Javascript Question

Javascript regex keeps returning false

I have a problem with regex in Javascript.
I need to retrieve an IP address from a String.
I tested my regex with regex101.com and everything works fine.

Here's my regex :

var regex = new RegExp('(\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b:[0-9]+)|(localhost:[0-9]+)', 'i');

And here's the snippet I have


Result is always false.

I tried several methods, string.match, the regex package v0.1.1 also.

Is there something I am missing ?

Thank you.

Answer Source

The problem is just that you haven't escaped your backslashes.

var regex = new RegExp('(\\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\\b:[0-9]+)|(localhost:[0-9]+)', 'i');

> true

The fundamental problem here is that the backslash has special meaning as an escape character, both to JavaScript and to RegExp.

So, when JavaScript sees your '\b', it interprets it as an escape character - in this case a backspace character. This interpretation happens before it gets to the RegExp engine.

So, you need to escape your backslashes by doubling them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download