0

那么答案应该很简单。但我是正则表达式的新手。

我想做的只是查找和替换:

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

将上述句子中的“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);
4

5 回答 5

4

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

var string2 = string.replace(/\bof\b/g, "in");
于 2013-06-22T11:49:21.977 回答
2

为什么不简单var replaced = yourString.replace(/of/g, 'in');

于 2013-06-22T11:51:11.983 回答
1

不使用正则表达式进行全局替换。

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');
于 2013-06-22T11:49:55.560 回答
0

像这样?

str.replace("of","in");
于 2013-06-22T11:50:26.440 回答
0

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

所以:

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

或者:

new Regexp("(\\w*\\W*)of(\\w*\\W*)","g");
于 2013-06-22T11:49:17.680 回答