I'd consider myself adept at understanding regular expressions; for the first time, I've been stumped, and the last 20 minutes of googling/searching SO for the answer has yielded nothing.
Consider the string:
var string = "Friends of mine are from France and they love to frolic."
And I want to replace or capture (or do something with) every occurrence of "fr" (case insensitive).
I could use, simply:
var replaced = string.replace(/fr/gi);
However, what if I wanted to ignore the very first occurrence of "fr"? Ordinarily I'd use a positive lookbehind (say, (?<=.)fr
in php) to do this but our friend javascript doesn't do that. Without installing a third party library, is there any way to ensure my expression does NOT match at the start of line?
Update: While there are means of replacing with the captured $1
, my particular use-case is split()
here, and would require fixing up the array after the fact if I used something like @Explosion Pills' suggestion string.replace(/^(fr)|fr/gi, "$1");
string.split(/(?!^)fr/gi);
This leaves you with ["Friends of mine are ", "om ", "ance and they love to ", "olic."]
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