JavaScript Replace All Instances of a String
Publikováno: 1.12.2018
I've started building out our JavaScript Glossary and when I got to the rep...
I've started building out our JavaScript Glossary and when I got to the replace() method, I had to build out a snippet to handle replacing all occurrences of a string in a string.
Only Replaces One
https://scotch.io/embed/gist/7be587f89ba2ee18f105a57a791a2c18
Replaces All with literal regular expression
Normally String replace() only replaces the first instance it finds. If we want JavaScript to replace all, we'll have to use a regular expression using /g
.
https://scotch.io/embed/gist/452b0b9c2ff1d4ddf1ae3449f90ef595
Using RegExp()
In addition to using the inline /g
, we can use the constructor function of the RegExp object.
myMessage.replace(new RegExp('sentence', 'g'), 'message');
https://scotch.io/embed/gist/fcd4396ee879d3ccc306512a59e2608a
Replacing Special Characters
To replace special characters like -/\^$*+?.()|[]{})
we'll need to use a \ backslash to escape them.
Here we'll replace all the -
in this string with just -
. I ran into this when building out the Scotch dashboard with markdown trying to escape all my symbols.
// replace - with -
myUrl.replace(/-/g, '-');
// or with RegExp
myUrl.replace(new RegExp('-', 'g'), '-');
https://scotch.io/embed/gist/d1d233fb4ff5264cd50b8208a03dcf84