如何使用JavaScript替换字符串中的所有点

JavaScript

泡芙猪猪

2020-03-16

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

例如,我有:

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

我想得到:okay this is a string

到目前为止,我尝试了:

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

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

第1705篇《如何使用JavaScript替换字符串中的所有点》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
JinJinEva 2020.03.16
String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

    while(word.indexOf(character) != -1)
        word = word.replace(character,replaceChar);

    return word;
}
Mandy樱 2020.03.16
str.replace(new RegExp(".","gm")," ")
Near村村 2020.03.16

我在点上添加双反斜杠以使其起作用。欢呼。

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
路易斯丁神奇 2020.03.16

对于这种简单的情况,我还建议使用javascript内置的方法。

您可以尝试这样:

"okay.this.is.a.string".split(".").join("")

问候

Davaid阳光伽罗 2020.03.16

您需要对进行转义,.因为它在正则表达式中具有“任意字符”的含义。

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android