Search code examples
javascriptregex

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?


Solution

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