Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS replacing all occurrences of string using variable [duplicate]

I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this

function name(str,replaceWhat,replaceTo){     str.replace(/replaceWhat/g,replaceTo); } 

How can i use a variable in the first argument?

like image 326
usama8800 Avatar asked Jul 23 '13 20:07

usama8800


People also ask

How will you replace all occurrences of a string in JavaScript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

How do you replace all occurrences in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do I replace multiple characters in a string?

If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.

Does JavaScript have replaceAll?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.


1 Answers

The RegExp constructor takes a string and creates a regular expression out of it.

function name(str,replaceWhat,replaceTo){     var re = new RegExp(replaceWhat, 'g');     return str.replace(re,replaceTo); } 

If replaceWhat might contain characters that are special in regular expressions, you can do:

function name(str,replaceWhat,replaceTo){     replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');     var re = new RegExp(replaceWhat, 'g');     return str.replace(re,replaceTo); } 

See Is there a RegExp.escape function in Javascript?

like image 153
Barmar Avatar answered Sep 23 '22 05:09

Barmar