我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
当前回答
对于这个简单的场景,我也建议使用javascript内置的方法。
你可以试试这个:
"okay.this.is.a.string".split(".").join("")
问候
其他回答
还有一个很容易理解的解决方案:)
var newstring = mystring.split('.').join(' ');
您可以使用RegExp javascript对象替换任何字符串/字符的所有出现。
这是代码,
var mystring = 'okay.this.is.a.string';
var patt = new RegExp("\\.");
while(patt.test(mystring)){
mystring = mystring .replace(".","");
}
对于这个简单的场景,我也建议使用javascript内置的方法。
你可以试试这个:
"okay.this.is.a.string".split(".").join("")
问候
这更简洁/可读,应该比Fagner Brack发布的更好(toLowerCase不是在循环中执行的):
String.prototype.replaceAll = function(search, replace, ignoreCase) {
if (ignoreCase) {
var result = [];
var _string = this.toLowerCase();
var _search = search.toLowerCase();
var start = 0, match, length = _search.length;
while ((match = _string.indexOf(_search, start)) >= 0) {
result.push(this.slice(start, match));
start = match + length;
}
result.push(this.slice(start));
} else {
result = this.split(search);
}
return result.join(replace);
}
用法:
alert('Bananas And Bran'.replaceAll('An', '(an)'));
让a = "从前有一个国王。opeator传播。让。版本。const。”;
let data = a.r eall (".","");
答案:data = "曾经有一个king spread operator let ver const";
您需要对该字符串使用replaceAll()方法。