photonacl
photonacl

Reputation: 135

Why is this Regex not working for JavaScript?

The code is suppose to say matched! for the given string. I tried multiple things and cannot get it to work.

HTML:

<div id="ssn">123-45-6789</div>

js:

var regex = new RegExp("^\d{3}-\d{2}-\d{4}$");

$("#div")
    .filter(function() {
        return this.innerHTML.match(regex);
    })
    .html("Matched!")
;

Upvotes: 0

Views: 53

Answers (1)

Pointy
Pointy

Reputation: 413702

Use native regular expression syntax when you can:

var regex = /^\d{3}-\d{2}-\d{4}$/;

When you construct a regular expression from a string, you have to double-up on the \ characters because it's a metacharacter in string constant token syntax too. If you don't, then by the time JavaScript passes the regular expression string to the RegExp constructor, the backslashes are gone.

You'd probably be better off using .test() in your filter function:

$("#div")
    .filter(function() {
        return regex.test(this.innerHTML);
    })
    .html("Matched!")
;

Upvotes: 4

Related Questions