替换字符串中的所有匹配项

时间:2011-05-19 21:13:54

标签: javascript regex

  

可能重复:
  Fastest method to replace all instances of a character in a string

如何替换字符串中的所有匹配项?

如果要替换字符串中的所有换行符(\ n)..

这只会替换第一次出现的换行符

str.replace(/\\n/, '<br />');

我无法弄清楚如何做到这一点?

3 个答案:

答案 0 :(得分:123)

使用全局标记。

str.replace(/\n/g, '<br />');

答案 1 :(得分:38)

Brighams回答使用literal regexp

使用Regex对象的解决方案。

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

在这里尝试:JSFiddle Working Example

答案 2 :(得分:-1)

正如here所述,您可以使用:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

...然后您可以使用以下方式致电:

var str = "50.000.000";
alert(replaceall(str,'.',''));

该功能将提醒“50000000”