Aiden
Aiden

Reputation: 1247

Why do I have to add double backslash on javascript regex?

When I use a tool like regexpal.com it let's me use regex as I am used to. So for example I want to check a text if there is a match for a word that is at least 3 letters long and ends with a white space so it will match 'now ', 'noww ' and so on.

On regexpal.com this regex works \w{3,}\s this matches both the words above.

But on javascript I have to add double backslashes before w and s. Like this:

var regexp = new RegExp('\\w{3,}\\s','i');

or else it does not work. I looked around for answers and searched for double backslash javascript regex but all I got was completely different topics about how to escape backslash and so on. Does someone have an explanation for this?

Upvotes: 7

Views: 1906

Answers (3)

Alexandre_Cbt
Alexandre_Cbt

Reputation: 41

The problem here is related to the handling of escape sequences in strings. In JavaScript, the backslash () is an escape character, so "\d" in the string becomes just "d".

To create the regular expression you intended, you need to escape the backslash itself. That is, instead of "\d", you should use "\\d":

Here's the corrected version of your function:

valueGet();
function valueGet() {
    let rgxValue= new RegExp('<myTag myAttrib="\\d+"');
    let myContent='<myTag myAttrib="27"';
    if (rgxValue.test(myContent)) {
        console.log("Match");
    } else {
        console.log("No match");
    }
}

Upvotes: 2

RobG
RobG

Reputation: 147523

Why? Because in a string, "\" quotes the following character so "\w" is seen as "w". It essentially says "treat the next character literally and don't interpret it".

To avoid that, the "\" must be quoted too, so "\\w" is seen by the regular expression parser as "\w".

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174874

You could write the regex without double backslash but you need to put the regex inside forward slashshes as delimiter.

/^\w{3,}\s$/.test('foo ')

Anchors ^ (matches the start of the line boundary), $ (matches the end of a line) helps to do an exact string match. You don't need an i modifier since \w matches both upper and lower case letters.

Upvotes: 4

Related Questions