Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex match *not* start of line

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");

like image 853
brandonscript Avatar asked Dec 18 '13 00:12

brandonscript


1 Answers

string.split(/(?!^)fr/gi);

This leaves you with ["Friends of mine are ", "om ", "ance and they love to ", "olic."]

like image 118
Matt Avatar answered Sep 21 '22 14:09

Matt