2

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 $?

2
  • Doesn't your function already do that? 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 the global flag if you want global replacement. Commented Nov 29, 2011 at 20:36

3 Answers 3

9
function r(t, o, n) {
    return t.split(o).join(n);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

0

Use a RegExp object instead of a simple string:

text.replace(new RegExp(oldChar, 'g'), newChar);

5 Comments

Fails for: var text = "^xxx^"; text.replace(new RegExp("^", 'g'), "$");
Note that you'll need to escape the character in case it's a special regex char, e.g. "\", ".", "(", etc. Thus new RegExp("\\"+oldChar,"g")
@Phrogz that requires a list of all possible escaping sequences as I don't know what is coming on the parameter
You would have to escape the ^ with two backslashes to make it work: var text = "^xxx^"; text.replace(new RegExp("\\^", 'g'), "$");
@BrunoLM You are right; while JS will allow /\z/ and treat it the same as /z/, there are a few broken cases such as /\x/ being treated as an empty hexadecimal character instead of just an /x/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.