Javascript 使用正则表达式查找和替换
答案应该很简单,但我对正则表达式不太熟悉 我想做的就是找到并替换: 例如:iti$%sa12c@#ombina#tion.43of/.45simp5./l7e5和SP75e$%cial23$% 在上句中,将“of”改为“In” 我试过了,但是没有结果,请帮我解决Javascript 使用正则表达式查找和替换,javascript,regex,Javascript,Regex,答案应该很简单,但我对正则表达式不太熟悉 我想做的就是找到并替换: 例如:iti$%sa12c@#ombina#tion.43of/.45simp5./l7e5和SP75e$%cial23$% 在上句中,将“of”改为“In” 我试过了,但是没有结果,请帮我解决 string="iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters"; var string2=string.replace("/(
string="iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters";
var string2=string.replace("/(\w*\W*)of(\w*\W*)/g","$1in$2");
console.warn(string2);
正则表达式是JavaScript中的文字或对象,而不是字符串 因此: 或: 修复(无引号)并使用单词边界(
\b
,无需使用$1
和$2
):
全局替换而不使用正则表达式
function replaceMulti(myword, word, replacement) {
return myword.split(word).join(replacement);
}
var inputString = 'iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters';
var outputString = replaceMulti(inputString, 'of', 'in');
像这样
str.replace("of","in");
为什么不是一个简单的
var-replaced=yourString.replace(/of/g,'in')代码>?这将只替换一次出现,而不是全部。这也不会替换“单词”,因为当不是完整单词时,这也会匹配“of”。这不会替换“单词”,因为当不是完整单词时,这也会匹配“of”。此外,这不是Haskell。这不会替换“单词”,因为当不是完整单词时,这也会匹配“of”。
var string2 = string.replace(/\bof\b/g, "in");
function replaceMulti(myword, word, replacement) {
return myword.split(word).join(replacement);
}
var inputString = 'iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters';
var outputString = replaceMulti(inputString, 'of', 'in');
str.replace("of","in");