最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace all characters in a string? - Stack Overflow

programmeradmin5浏览0评论

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

Share Improve this question asked Nov 29, 2011 at 20:27 BrunoLMBrunoLM 100k86 gold badges309 silver badges461 bronze badges 2
  • 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 the global flag if you want global replacement. – Phrogz Commented Nov 29, 2011 at 20:36
Add a ment  | 

3 Answers 3

Reset to default 9
function 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);
发布评论

评论列表(0)

  1. 暂无评论