3

I have what I think are the same expressions one in the sorthand regex format, the other as a RegExp object with a string. I expect they would both be true but that's not what I'm seeing.

/^key$|^key([;,]\skey)+$/.test('key, key; key') //true

var rgxStr = '^key$|^key([;,]\skey)+$'; //
(new RegExp(rgxStr)).test('key, key; key'); //false

What is going on?

2 Answers 2

3

Look here:

var rgxStr = '^key$|^key([;,]\skey)+$';
//                           ^ whoa, a backslash!

In a regular expression literal, JavaScript interprets that backslash as part of the regular expression.
In a normal string literal, JavaScript doesn't know what to do with \s and discards the backslash.

To fix it, escape your backslash in the string literal:

var rgxStr = '^key$|^key([;,]\\skey)+$';
Sign up to request clarification or add additional context in comments.

Comments

2

As soon as you're defining regexp in a string - you have to escape backslashes

var rgxStr = '^key$|^key([;,]\\skey)+$';

1 Comment

Ha, that's it. It's the double edged sword of coding late at night.

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.