JavaScript string replace, every instance. No, every fucking instance!

If you wish to replace all instances of “foo” with “bar” in yourString using JavaScript, here’s how you do it:

yourNewstring = yourString.replace(/foo/g,"bar");

How’s that for elegance, simplicity and readability?

Fucking JavaScript.

Note that foo’s really just foo, no quotes or nothing even if it has whitespace in it – it’s treated as a so called regular expression and not a variable, because of the slashes surrounding it.

Every time I’m writing JavaScript it feels like drinking tar, and to make matters worse it seems that good, easy access JavaScript documentation online is sparse.

The title is a slightly formatted version of a search I ended up trying in frustration, desperately seeking the answer to how to do just that: replace every instance of substring with another in a given string. It sounded like a simple enough task to do, and as it turned out, it was relatively so, at least compared to how incredibly difficult it seems to be to articulate it, judging by the poor results my other, more targeted and not-so-desperate searches gave me.