13
var badCode = "\(INST1,\\[0,";
var regex = new RegExp(badCode, "igm");

gets "unterminated character class" error.

How to fix?

TIA

trying suggestions from responders to this post, please see the following screen prints (you might have to right-click on images and open in new tab to make legible): note values of new_bad_thing (equiv of badCode above)

and here is the screen print when I hit the run button (please note the error message):

enter image description here

1
  • I get SyntaxError: Invalid regular expression: /(INST1,\[0,/: Unterminated group, i.e. the parenthesis (char 1 in string) doesn't have a matching ). It is being treated as a group as "\(" === "(", you need to write "\\(" to get \(. Commented Feb 1, 2013 at 4:21

2 Answers 2

12

Put another backslash at badCode:

var badCode = "\\(INST1,\\[0,";
var regex = new RegExp(badCode, "igm");

since you need one to escape ( inside the regex itself (signal it that it's a literal parentheis) and one escape for javascript.

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

4 Comments

Tried that, badCode = "\\(INST1,\\[0,", still getting "unterminated character class". Verified that badCode is what you showed in chrome debugger.
That's odd. See this fiddle which demonstrates it works.
you're right. And yet, as you see from my screen shots, that's what I'm getting. Could it be a bug in chrome?
Found the problem: even tho the debugger shows the "new_bad_thing" string as being the same as your "badcode", the chaining of the ".replace(/\\/g,"\\\\")" is causing the problem. When I take it out, the code works.
3

No, it gets "unterminated parenthetical", because you've forgotten to escape the backslash. Why not use a regular expression literal?

var regex = /\(INST1,\[0,/igm;

6 Comments

because badCode can be any number of things, I'm just using a literal as an example
@davej: Then escape the first backslash with another backslash. But the error can't be "unterminated character class" with that string. Something is awry.
thanks for your input, I edited the original post to show what I'm getting.
@davej: It seems like the replacements should be \\) and \\(, not \\\\) and \\\\(.
that's what I had originally, but I changed it match ofer zelig's solution
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.