繁体   English   中英

使用正则表达式查找和替换

[英]Find and Replace using Regular Expression

答案应该很简单。但是我对正则表达式并不陌生。

我想做的就是找到并替换:

例如:iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%characters

在以上句子中,将“ of”改为“ in”

我尝试了此操作,但没有得到结果,请帮帮我。

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);

修复正则表达式文字 (不加引号)并使用单词边界( \\b ,无需使用$1$2 ):

var string2 = string.replace(/\bof\b/g, "in");

为什么不var replaced = yourString.replace(/of/g, 'in');一个简单的var replaced = yourString.replace(/of/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');

正则表达式是JavaScript中的文字或对象,而不是字符串。

所以:

/(\w*\W*)of(\w*\W*)/g

要么:

new Regexp("(\\w*\\W*)of(\\w*\\W*)","g");

像这样?

str.replace("of","in");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM