What am I doing wrong here?
I’m trying to replace a number in a string with another number using javascript. I have a long string that has the number 1 in it several times. I need to replace the number 1 with 2 in every case except where 1 has another number on either side. I did a bunch of google searches for how to use regex (I’m totally new to regex) and I came up with this.
string.replace(/(?<!\d)1(?!\d)/,2);
Basically, I want the regex to match (and thus replace) every occurrence of the number 1 where it is surrounded by anything except another number. I don’t want the match to include the surrounding characters–only the number 1.
I keep getting the invalid quantifier error in my firebug console. What am I doing wrong?
It’s this bit:
(?<!\d). There’s no(?<, only(?:,(?=, and(?!.JavaScript doesn’t have look-behind, but I think you can work around it in this case, like this:
That captures the character immediately prior to the digit, then echoes it back (
$1in the replacement string) followed by the new content (2). The^near the beginning allows for the digit being the first character in the string.Live example
Breaking it down:
And in the replacement,
$12is not “replace with capture group 12” (which is what it looks like to me), but “replace with capture group 1 followed by the digit 2.”