1

Hi I have the following regular expression in JavaScript:

var re = new RegExp("\\[(\\d{8})([,|;]\\s*\\d{8})*\\]", "g");

When I set variables to equal the first and last bracket (with escape characters), which I get from attributes of an element and pass those variables to RegExp like this:



HTML:

div id="myid" left="\\[" right="\\]"/>

JavaScript:

bs = $("#myid");
left =  bs.attr('left');
right = bs.attr('right');

var re = new RegExp(left + "(\\d{8})([,|;]\\s*\\d{8})*" + right, "g");

I get the error message:

Uncaught SyntaxError: Invalid regular expression: /\\[(\d{8})([,|;]\s*\d{8})*\\]/: Unmatched ')' 

What am I doing wrong here?

Thanks

5
  • Chrome, Mac OS X - works. Commented Dec 10, 2013 at 0:13
  • Also works for me Chrome, Windows. Commented Dec 10, 2013 at 0:16
  • Hmm, it seems to work when you explicitly set the variable. However I'm getting the variable from the attribute of an element. See my edited question. Does this work for you guys? Commented Dec 10, 2013 at 0:18
  • 2
    OK, now you've completely changed the question -- what is the html on $('#myid');? Commented Dec 10, 2013 at 0:19
  • With your update, see @Adassko's answer. I think it will fix it. Commented Dec 10, 2013 at 0:30

1 Answer 1

2

you don't need to escape your escape sign in html attributes

Those are only needed in javascript's strings.

Just replace

\\[

with single

\[

in your attributes.

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

3 Comments

Assuming the html originally looked like <div id='myid' left="\\[" right="\\]"></div> this is definitely the right answer. Moreover, the defined regex is actually double escaping everything including \d, \s. Should look like left + "(\d{8})([,|;]\s*\d{8})*" + right instead.
@r3mus: not true - you need to double escape everything here - once for javascript and once for regexp. There's two ways of defining a regular expression in javascript - in string like in the example above or between slashes like /(\d{8})([,|;]\s*\d{8})*/ - in this case you don't need to add extra slashes
Oh, indeed you're correct. left + "(\\d{8})([,|;]\\s*\\d{8})*" + right is correct.

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.