我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
当前回答
简单的方法
“先生”.split (' . ') . join (" ");
..............
控制台
其他回答
mystring.replace(new RegExp('.', "g"), ' ');
简单的方法
“先生”.split (' . ') . join (" ");
..............
控制台
@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(/</g, "<")
.replace(/>/g, ">")
.replace(/\./g,' ')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
String.prototype.replaceAll = function (needle, replacement) {
return this.replace(new RegExp(needle, 'g'), replacement);
};