admin管理员组

文章数量:1335513

When I use a tool like regexpal 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 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 pletely different topics about how to escape backslash and so on. Does someone have an explanation for this?

When I use a tool like regexpal. 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. 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 pletely different topics about how to escape backslash and so on. Does someone have an explanation for this?

Share Improve this question asked Apr 4, 2015 at 2:45 AidenAiden 1,2472 gold badges13 silver badges26 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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".

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 bees 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");
    }
}

本文标签: Why do I have to add double backslash on javascript regexStack Overflow