How to replace all dots in a string using JavaScri

2019-01-01 04:46发布

I want to replace all the occurrences of a dot(.) in a JavaScript string

For example, I have:

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

I want to get: okay this is a string.

So far I tried:

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

but this ends up with all the string replaced to spaces.

14条回答
何处买醉
2楼-- · 2019-01-01 05:07
String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

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

    return word;
}
查看更多
情到深处是孤独
3楼-- · 2019-01-01 05:08
str.replace(new RegExp(".","gm")," ")
查看更多
冷夜・残月
4楼-- · 2019-01-01 05:09

I add double backslash to the dot to make it work. Cheer.

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
查看更多
回忆,回不去的记忆
5楼-- · 2019-01-01 05:13

Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this

var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'
查看更多
高级女魔头
6楼-- · 2019-01-01 05:15

One more solution which is easy to understand :)

var newstring = mystring.split('.').join(' ');
查看更多
不再属于我。
7楼-- · 2019-01-01 05:21
String.prototype.replaceAll = function (needle, replacement) {
    return this.replace(new RegExp(needle, 'g'), replacement);
};
查看更多
登录 后发表回答