Regex: Replace foo if it's a word or inside a URL

javascript, regex

Solution

You can use this code (works well with your example but haven't tried with more complex inputs):

str = 'foo myfoo http://thefoobar.com/food is 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 is awesome

Live Demo: http://ideone.com/8xGy2h

Problem

Given this: ``` str = "foo myfoo http://thefoobar.com/food is awesome"; str.replace(magicalRegex, 'bar'); ``` The expected result is: ``` "bar myfoo http://thebarbar.com/bard is awesome" ``` I get the `\b(foo)\b` part, but I can't figure out how to match and capture `foo` from within a url. For these purposes, assume urls always start with `http`. Any help?

Original source