简体   繁体   English

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

[英]Find and Replace using Regular Expression

Well the answer should be very simple.But i am new to the regular expression. 答案应该很简单。但是我对正则表达式并不陌生。

What i want to do is just find and replace : 我想做的就是找到并替换:

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

In the above sentence replace the words "of" with "in" 在以上句子中,将“ of”改为“ in”

I tried this but didn't get the result, please help me out. 我尝试了此操作,但没有得到结果,请帮帮我。

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

Why not a simple var replaced = yourString.replace(/of/g, 'in'); 为什么不var replaced = yourString.replace(/of/g, 'in');一个简单的var replaced = yourString.replace(/of/g, 'in'); ?

Globally replace without using a regex. 全局替换而不使用正则表达式。

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

Regular expressions are literals or objects in JavaScript, not strings. 正则表达式是JavaScript中的文字或对象,而不是字符串。

So: 所以:

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

or: 要么:

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