javascript - Regex: Replace foo if it's a word or inside a URL -
given this:
str = "foo myfoo http://thefoobar.com/food awesome"; str.replace(magicalregex, 'bar');
the expected result is:
"bar myfoo http://thebarbar.com/bard awesome"
i \b(foo)\b
part, can't figure out how match , capture foo
within url. these purposes, assume urls start http
.
any help?
you can use code (works example haven't tried more complex inputs):
str = 'foo myfoo http://thefoobar.com/food awesome'; str = str.replace(/\bfoo\b/g, 'bar'); while (/http:\/\/[^\s]*?foo/.test(str)) str = str.replace(/(http:\/\/[^\s]*?)?foo/g, function($0, $1) { return $1 ? $1 + 'bar' : $0; }); console.log(str);
output:
bar myfoo http://thebarbar.com/bard awesome
Comments
Post a Comment