我想替换JavaScript字符串中出现的所有点(.)

例如,我有:

var mystring = 'okay.this.is.a.string';

我想要得到:这是一个字符串。

到目前为止,我尝试了:

mystring.replace(/./g,' ')

但这最终将所有字符串替换为空格。


当前回答

下面是replaceAll的另一个实现。希望它能帮助到别人。

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

然后你可以使用它:

var myText =“我的名字是乔治”; var newText = myText。replaceAll(“乔治”,“迈克尔”);

其他回答

补充(搜索,补充)[MDN]

 ".a.b.c.".replaceAll('.', ' ')
 // result: " a b c "

 // Using RegEx. You MUST use a global RegEx.
 ".a.b.c.".replaceAll(/\./g, ' ')
 // result: " a b c "
    

replaceAll()用replaceWith替换所有出现的搜索。

它实际上与使用全局regex(*)的replace() [MDN]相同,在我的视图中,仅仅是replaceAll()更具可读性。

(*)表示它将匹配所有的事件。


重要(!)如果你选择regex:

当使用regexp时,你必须设置全局(“g”)标志; 否则,它将抛出TypeError: "replaceAll必须被调用 一个全局RegExp”。

mystring.replace(new RegExp('.', "g"), ' ');

@scripto变得更简洁,没有原型:

function strReplaceAll(s, stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return s;
    for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
        s = s.replace(stringToFind, stringToReplace);
    return s;
}

以下是它的累积情况:http://jsperf.com/replace-vs-split-join-vs-replaceall/68

var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);

function escapeHtml(text) {
if('' !== text) {
    return text.replace(/&/g, "&")
               .replace(/&lt;/g, "<")
               .replace(/&gt;/g, ">")
               .replace(/\./g,' ')
               .replace(/&quot;/g, '"')
               .replace(/&#39/g, "'");
} 

您可以使用RegExp javascript对象替换任何字符串/字符的所有出现。

这是代码,

var mystring = 'okay.this.is.a.string';

var patt = new RegExp("\\.");

while(patt.test(mystring)){

  mystring  = mystring .replace(".","");

}