x.replace(/old/gi. 'new');
x.replace(/whatever/gi. 'whatevernew');
x.replace(/car/gi. 'boat');
有没有办法在一个正则表达式语句和新旧单词数组中组合它们。 PHP解决方案也很受欢迎。
答案 0 :(得分:2)
你可以这样做:
var x = 'The old car is just whatever';
var arr = [{ old: /old/gi, new: 'new' },
{ old: /whatever/gi, new: 'whatevernew' },
{ old: /car/gi, new: 'boat' }];
for (var ii = 0; ii < arr.length; ii++) {
x = x.replace(arr[ii].old, arr[ii].new);
}
答案 1 :(得分:2)
lbu和RobG使用回调提出了一种有趣的方法。这里有一个更通用的版本,你可以使用一个函数来获取你想要替换的内容的数据结构以及你想要用它作为参数替换它的内容。
function multiReplace(str, params) {
var regStr = "";
for (var i in params) {
regStr += "(" + i + ")|"; // build regEx string
}
regStr = regStr.slice(0, -1); // remove extra trailing |
return(str.replace(new RegExp(regStr, "gi"), function(a) {
return(params[a]);
}));
}
var test = 'This old car is just whatever and really old';
var replaceParam = {"old": "new", "whatever": "something", "car": "boat"};
var result = multiReplace(test, replaceParam);
alert(result);
这是一个表明它在行动的小提琴:http://jsfiddle.net/jfriend00/p8wKH/
答案 2 :(得分:1)
试试这个:
var regexes = { 'new': /old/gi, 'whatevernew': /whatever/gi, 'boat': /car/gi };
$.each(regexes, function(newone, regex){
x = x.replace(regex, newone);
});
或者这个:
var regexes = { 'old':'new', 'whatever':'whatevernew', 'car':'boat'};
$.each(regexes, function(oldone, newone){
x = x.replace(new RegExp(oldone, 'gi'), newone);
});
答案 3 :(得分:1)
replace方法支持使用回调函数:
var x = 'This old car is just whatever';
var y = x.replace(/(old)|(whatever)|(car)/gi,function (a) {
var str = "";
switch(a){
case "old":
str = "new";
break;
case "whatever":
str = "something";
break;
case "car":
str = "boat";
break;
default:
str= "";
}
return str;
});
alert(y);
// Y will print "This new car is just something"
答案 4 :(得分:1)
这里还有几个:
// Multi RegExp version
var replaceSeveral = (function() {
var data = {old:'new', whatever: 'whatevernew', car: 'boat'};
return function(s) {
var re;
for (var p in data) {
if (data.hasOwnProperty(p)) {
re = new RegExp('(^|\\b)' + p + '(\\b|$)','ig');
s = s.replace(re, '$1' + data[p] + '$2');
}
}
return s;
}
}());
// Replace function version
var comparitor = (function() {
var data = {old:'new', whatever: 'whatevernew', car: 'boat'};
return function (word) {
return data.hasOwnProperty(word.toLowerCase())? data[word] : word;
}
}());
var s = 'old this old whatever is a car';
alert(
s
+ '\n' + replaceSeveral(s)
+ '\n' + s.replace(/\w+/ig, comparitor)
);
答案 5 :(得分:1)
Ibu的回调解决方案非常简洁,但可以进一步简化:
x = x.replace(/\b(?:old|whatever|car)\b/gi,
function (m0) {
return {'old': 'new',
'car': 'boat',
'whatever': 'something'}[m0];
});
这种使用对象文字的技巧非常有效。我通过添加字边界来修改正则表达式以仅匹配整个单词(以避免将gold
更改为gnew
等。)