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:
str = str.replace(/(^|\D)1(?!\d)/g, "$12")
That captures the character immediately prior to the digit, then echoes it back ($1 in 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:
(^|\D) Match either start-of-string, or a non-digit, and capture the result 1 Match the digit 1... (?!\d) ...but only if it isn't followed by a digit
And in the replacement, $12 is 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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With