我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
当前回答
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
其他回答
String.prototype.replaceAll = function (needle, replacement) {
return this.replace(new RegExp(needle, 'g'), replacement);
};
你需要逃离。因为它在正则表达式中具有“任意字符”的含义。
mystring = mystring.replace(/\./g,' ')
还有一个很容易理解的解决方案:)
var newstring = mystring.split('.').join(' ');
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
简单的方法
“先生”.split (' . ') . join (" ");
..............
控制台