34

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?

0

2 Answers 2

65

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?

Sign up to request clarification or add additional context in comments.

9 Comments

This doesn't work as expected if replaceWhat contains regexp metacharacters, e.g. *, +, [.
@pts So does a literal regexp.
Then add this logic in as well: Is there a RegExp.escape function in Javascript?
If used like the asker intended, this will give wrong results if metacharacters appear in replaceWhat. So better chose another answer!
@thatOneGuy Good catch, I've added a return to the functions. I was obviously focused on the regexp part, not the replace part.
|
0

The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags


Replace has an alternate form that takes 3 parameters and accepts a string:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

4 Comments

This is Firefox-specific, in Chrome it replaces only the first occurrence.
True... it had the "nonstandard" flag.
remember, you need to bind this to a new variable : stackoverflow.com/questions/12231644/…
@Hogan this is not working currently please remove this answer or update with working solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.