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
pattern
is a string, only the first occurrence ofpattern
will be replaced. -
If
pattern
is aRegExp
, by default it will replace the first occurrence, unless you pass the global flag to the pattern. So if I wanted to replaceasdf
in withhjkl
in a string,replace(/asdf/, "hjkl")
will replace just the first occurrence. To replace all occurrences, it needs to bereplace(/adsf/g, "hjkl)
(note the globalg
flag in the regex).
So maybe the moral of the story is to always use a regex (and remember your flags!).