Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

myString.replace( VARIABLE, "") ...... but globally

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?

like image 465
monkey blot Avatar asked Apr 13 '12 06:04

monkey blot


People also ask

Does replace replace all occurrences?

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.

Does string replace replace all instances?

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.

How do you change a string variable?

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.


1 Answers

Well, you can use this:

var reg = new RegExp(oldWord, "g"); myString.replace(reg, ""); 

or simply:

myString.replace(new RegExp(oldWord, "g"), ""); 
like image 150
Derek 朕會功夫 Avatar answered Oct 04 '22 05:10

Derek 朕會功夫