2

I am making a program that gets an input from the user, then makes a regular expression using that input.

Here is some example code:

<input id="a" type="text" />
<input type="button" value="Create" id="b" />
<script>
(function (z , code) {
    var input = document.getElementById("a"),
        b = document.getElementById("b");
    function primary(){
        var regEx = new RegExp("[A-Z]{3}[ ]\d{9}[ ]" + input.value.toUpperCase(), "g");
        alert(regEx);
    };
    b.addEventListener("click",function(){
        primary();
    }, false);
}(this, document));
</script>

FIDDLE

It works accept for this:

Say I use FooBar as my input. Instead of creating a regular expression that says, /[A-Z]{3}[ ]\d{9}[ ]FOOBAR/g I get a regular expression that says, /[A-Z]{3}[ ]d{9}[ ]FOOBAR/g. A d instead of \d.

Why is this not working properly? How can I correct this?

Thank you.

2
  • When you use the regex constructor you need to double escape special charaters, so \\d, etc. Commented Jan 23, 2014 at 3:45
  • @elclanrs Thanks! That sure fixed it! If you posted that as an answer I could mark it as correct. Commented Jan 23, 2014 at 3:47

1 Answer 1

2

As per the MDN RegExp docs,

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

var re = /\w+/;
var re = new RegExp("\\w+");

In your RegEx, \d is a special character

\d Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].

For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."

So, your RegEx, should have been like this

[A-Z]{3}[ ]\\d{9}[ ]   //\\d instead of \d
Sign up to request clarification or add additional context in comments.

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.