7

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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thank you, but I don't understand why my question got -4. Did I do something wrong?
No idea, down voters who don't have the courage to explain their vote don't have any credence. Luckily it takes a lot of down votes to cancel an up vote. ;-)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.