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

davej
  • 1,350
  • 5
  • 17
  • 34
  • 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 `\(`. – Paul S. Feb 01 '13 at 04:21

2 Answers2

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.

Ofer Zelig
  • 17,068
  • 9
  • 59
  • 93
  • Tried that, badCode = "\\\(INST1,\\\[0,", still getting "unterminated character class". Verified that badCode is what you showed in chrome debugger. – davej Feb 01 '13 at 03:56
  • That's odd. See this [fiddle](http://jsfiddle.net/wdzV6/) which demonstrates it works. – Ofer Zelig Feb 01 '13 at 05:23
  • 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? – davej Feb 01 '13 at 14:15
  • 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. – davej Feb 01 '13 at 15:41
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;
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • because badCode can be any number of things, I'm just using a literal as an example – davej Feb 01 '13 at 03:59
  • @davej: Then escape the first backslash with another backslash. But the error can't be "unterminated character class" with that string. Something is awry. – Ry- Feb 01 '13 at 04:04
  • thanks for your input, I edited the original post to show what I'm getting. – davej Feb 01 '13 at 04:33
  • @davej: It seems like the replacements should be `\\)` and `\\(`, not `\\\\)` and `\\\\(`. – Ry- Feb 01 '13 at 05:33
  • that's what I had originally, but I changed it match ofer zelig's solution – davej Feb 01 '13 at 14:12
  • @davej: My mistake. `\\\\]` and `\\\\[` instead of `\\]` and `\\[`. It looks like the debugger or the watcher isn't re-escaping things. (It happens.) They do actually need to be quadruple-escaped. – Ry- Feb 01 '13 at 16:22