4

What is the simplest way in JS to replace multiple things in string at once (without them interfering)? Like

"tar pit".replaceArray(['tar', 'pit'], ['capitol', 'house']);

...so it produces "capitol house", not "cahouseol house"?

1
  • 1
    the simplest answer: regex Commented Sep 5, 2013 at 15:22

2 Answers 2

6
var replaceArray = function(str, from, to) {
   var obj = {}, regex;
   from.forEach(function(item, idx){obj[item] = to[idx];});

   regex = new RegExp('(' + from.join('|') + ')', 'g');
   return str.replace(regex, function(match){return obj[match]});
}

replaceArray("tar pit", ["tar", "pit"], ["capitol", "house"]);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for much better code than mine, cant see my code over you :).
2

how about this -

function replaceArray(text, toBeReplacedArray, replacementArray) {
    for (var i = 0; i < toBeReplacedArray.length; i++) {
        var re = new RegExp(toBeReplacedArray[i], 'g');
        text = text.replace(re, '__' + i + '__');

    }

    for (var i = 0; i < replacementArray.length; i++) {
        var re = new RegExp('__' + i + '__', 'g');
        text = text.replace(re, replacementArray[i]);
    }
    return text;
}

replaceArray("tar pit", ['tar', 'pit'], ['capitol', 'house']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.