Javascript 替换字符串中所有出现的地方

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6064956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:05:12  来源:igfitidea点击:

replace all occurrences in a string

javascriptregex

提问by clarkk

Possible Duplicate:
Fastest method to replace all instances of a character in a string

可能的重复:
替换字符串中一个字符的所有实例的最快方法

How can you replace all occurrences found in a string?

如何替换字符串中出现的所有内容?

If you want to replace all the newline characters (\n) in a string..

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

This will only replace the first occurrence of newline

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

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

I cant figure out how to do the trick?

我不知道如何做这个把戏?

回答by Brigham

Use the global flag.

使用全局标志。

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

回答by Kerem Baydo?an

Brighams answer uses literal regexp.

布里格姆斯的回答使用literal regexp.

Solution with a Regex object.

使用 Regex 对象的解决方案。

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

TRY IT HERE : JSFiddle Working Example

在这里尝试:JSFiddle 工作示例

回答by Dika Arta

As explained here, you can use:

正如解释在这里,你可以使用:

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

... which you can then call using:

...然后您可以使用以下方法调用它:

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

The function will alert "50000000"

该功能将提示“50000000”