-3

Would someone please explain me why this returns false?

var regex = new RegExp('\([0-9]{3}\)[0-9]{3}-[0-9]{4}');
return regex.test('(555)555-5555');

Is there some other RegExp property that I have to insert?

Is it better not to use the string and does it have any difference using the string or the regex literal?

0

1 Answer 1

1

It returns false because you need to escape the backslash when you define it as a string, like this:

var rePhoneNumber = new RegExp('\\([0-9]{3}\\)[0-9]{3}-[0-9]{4}');

But, since it is javascript, you can make a literal definition:

var rePhoneNumber = /\([0-9]{3}\)[0-9]{3}-[0-9]{4}/;
return rePhoneNumber.test('(555)555-5555');

Now it return true, since you don't need to escape the backslash.


See a working snippet here:

var rePhoneNumber = /\([0-9]{3}\)[0-9]{3}-[0-9]{4}/;
console.log(rePhoneNumber.test('(555)555-5555'));

var rePhoneNumber2 = new RegExp('\\([0-9]{3}\\)[0-9]{3}-[0-9]{4}');
console.log(rePhoneNumber2.test('(555)555-5555'));

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

4 Comments

how would I do that regex inside a string? Just for curiosity
@Jan What the.... Oh. Why didn't I think of that?
@some Some might have been in a hurry...
@CaioCésarSilvaGomes Added example of how to escape the string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.