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 $
?
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 $
?
- Doesn't your function already do that? – Tom van der Woerdt Commented Nov 29, 2011 at 20:32
-
@TomvanderWoerdt No, JavaScript's
String.prototype.replace
only replaces the first occurrence of strings; you need to use a regular expression with theg
lobal flag if you want global replacement. – Phrogz Commented Nov 29, 2011 at 20:36
3 Answers
Reset to default 9function r(t, o, n) {
return t.split(o).join(n);
}
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;
}
Use a RegExp object instead of a simple string:
text.replace(new RegExp(oldChar, 'g'), newChar);