How can I use a variable to remove all instances of a substring from a string? (to remove, I'm thinking the best way is to replace, with nothing, globally... right?)
if I have these 2 strings,
myString = "This sentence is an example sentence." oldWord = " sentence"
then something like this
myString.replace(oldWord, "");
only replaces the first instance of the variable in the string.
but if I add the global g like this myString.replace(/oldWord/g, "");
it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?
The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.
The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.
In JavaScript, replace() is a string method that is used to replace occurrences of a specified string or regular expression with a replacement string. Because the replace() method is a method of the String object, it must be invoked through a particular instance of the String class.
Well, you can use this:
var reg = new RegExp(oldWord, "g"); myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With