Reputation: 100331
I have a string that is passed by parameter and I have to replace all occurrences of it in another string, ex:
function r(text, oldChar, newChar)
{
return text.replace(oldChar, newChar); // , "g")
}
The characters passed could be any character, including ^
, |
, $
, [
, ]
, (
, )
...
Is there a method to replace, for example, all ^
from the string I ^like^ potatoes
with $
?
Upvotes: 2
Views: 1524
Reputation: 23806
Use a RegExp object instead of a simple string:
text.replace(new RegExp(oldChar, 'g'), newChar);
Upvotes: 0
Reputation: 3418
If you simply pass '^' to the JavaScript replace function it should be treated as a string and not as a regular expression. However, using this method, it will only replace the first character. A simple solution would be:
function r(text, oldChar, newChar)
{
var replacedText = text;
while(text.indexOf(oldChar) > -1)
{
replacedText = replacedText.replace(oldChar, newChar);
}
return replacedText;
}
Upvotes: 1