开发者

replace array of words

开发者 https://www.devze.com 2023-03-16 03:34 出处:网络
x.replace(/old/gi. \'new\'); x.replace(/whatever/gi. \'whatevernew\'); x.replace(/car/gi. \'boat\'); Is there a way to combine those in one regexp st开发者_如何学编程atement perhaps and array of old
x.replace(/old/gi. 'new');
x.replace(/whatever/gi. 'whatevernew');
x.replace(/car/gi. 'boat');

Is there a way to combine those in one regexp st开发者_如何学编程atement perhaps and array of old and new words. PHP solution is also welcome.


You could do something like this:

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


lbu and RobG present an interesting approach using the callback. Here's a little more general purpose version of that where you have a function that just takes a data structure of what you want to replace and what you want to replace it with as a parameter.

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

And a fiddle that shows it in action: http://jsfiddle.net/jfriend00/p8wKH/


Try this:

var regexes = { 'new': /old/gi, 'whatevernew': /whatever/gi, 'boat': /car/gi };

$.each(regexes, function(newone, regex){
  x = x.replace(regex, newone);
});

Or this:

var regexes = { 'old':'new', 'whatever':'whatevernew', 'car':'boat'};

$.each(regexes, function(oldone, newone){
  x = x.replace(new RegExp(oldone, 'gi'), newone);
});


Here's a couple more:

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

);


Ibu's callback solution is pretty clean, but can be further streamlined:

x = x.replace(/\b(?:old|whatever|car)\b/gi,
        function (m0) {
            return {'old': 'new',
                    'car': 'boat',
                    'whatever': 'something'}[m0];
        });

This technique of using an object literal is quite efficient. I modified the regex to match only whole words by adding word boundaries (to avoid changing gold to gnew etc).

EDIT: Upon closer inspection, I see that jfriend00's solution is using the same technique (and is generalized to be more useful).


the replace method supports using a a call back function:

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消