我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
我想替换JavaScript字符串中出现的所有点(.)
例如,我有:
var mystring = 'okay.this.is.a.string';
我想要得到:这是一个字符串。
到目前为止,我尝试了:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
当前回答
下面是replaceAll的另一个实现。希望它能帮助到别人。
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
然后你可以使用它:
var myText =“我的名字是乔治”; var newText = myText。replaceAll(“乔治”,“迈克尔”);
其他回答
str.replace(new RegExp(".","gm")," ")
你需要逃离。因为它在正则表达式中具有“任意字符”的含义。
mystring = mystring.replace(/\./g,' ')
还有一个很容易理解的解决方案:)
var newstring = mystring.split('.').join(' ');
我加了双反斜杠的点,使它工作。欢呼。
var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
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, "'");
}