String Replace in Javascript
I'm very used to ruby's gsub(pattern, replacement) that does a [g]lobal [sub]stitution on a string - that is, it replaces all occurrences of the pattern in the string. If you wanted to just replace the first occurrence of the pattern you could use sub, but I so rarely need to do that I forgot it existed.
Javascript's equivalent, replace, handles things a little bit differently. So much so I was surprised by it's behavior.
replace(pattern, replacement)
pattern can be a string or a RegExp, but you get different replacement behavior depending on which you use.
-
If
patternis a string, only the first occurrence ofpatternwill be replaced. -
If
patternis aRegExp, by default it will replace the first occurrence, unless you pass the global flag to the pattern. So if I wanted to replaceasdfin withhjklin a string,replace(/asdf/, "hjkl")will replace just the first occurrence. To replace all occurrences, it needs to bereplace(/adsf/g, "hjkl)(note the globalgflag in the regex).
So maybe the moral of the story is to always use a regex (and remember your flags!).
Docs: String.prototype.replace() - JavaScript | MDN
Tweet