0

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!")
;
1
  • Your <div> has the id "ssn", but your jQuery selector says "#div" ... Commented Jan 15, 2015 at 23:25

1 Answer 1

4

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!")
;
Sign up to request clarification or add additional context in comments.

4 Comments

Another point would be that $("#div") should actually be $("#ssn") as there is no element with id div in the example.
@Diego yes; I assumed that was just a transcription error.
wow thanks Pointy, worked like a charm! May I know what is the difference for .test() vs .match() ? Thanks.
@photonacl .test() just returns a boolean ("did it match or not?").

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.