I think you need to take many steps so that everything is done correctly. You basically do two separate (albeit similar) regular expressions:
- globally replacing the group of characters "foo" if it occurs inside a link, and
- global word replacement "foo" in the rest of the line.
This code will go through both stages separately (first the URL, the other lines the second) and give the final replacement:
var urlPattern = /(http:\/\/[^\s]+)/; var urlFooPattern = /(foo)/g; var globalFooPattern = /\b(foo)\b/g; var str = "foo myfoo http://thefoobar.com/food is awesome"; var urlString = str.match(urlPattern)[0]; urlString = urlString.replace(urlFooPattern, "bar"); str = str.replace(urlPattern, urlString); str = str.replace(globalFooPattern, "bar");
Note. . It is assumed that there is only one URL per line., To handle the possibility of multiple URLs would be a little more complicated:
- grab all urls using
var urlString = str.match(urlPattern) in an array - creating a new array by cycling through each URL and individually "replacing foo" on each
- Quoting through the original array of matches and using them as templates to replace with updated values ββin the second array
scrolling through all the URLs returned by var urlString = str.match(urlPattern) , replacing them with βfooβ individually and repeating them again, then replacing them in the original line one at a time.
source share