5

Coming from a PHP background, I am a little spoiled with the str_replace function which you can pass an array of haystacks & needles.

I have yet not seen such a function in Javascript, but I have managed to get the job done, altough ugly, with the below shown code:

return myString.replace(" ", "-").replace("&", ",");

However, as my need to replace certain characters with another character grows, I am sure that there's much better ways of accomplishing this - both performance-wise and prettier.

So what can I do instead?

Industrial
  • 41,400
  • 69
  • 194
  • 289
  • You could create a function, but I do not know a native javascript function that does it. – David Laberge Jan 24 '12 at 14:14
  • `myString.replace(" ", "-")` probably doesn't do what you want. `"foo bar baz".replace(" ", "-") === "foo-bar baz"`. Replace with a string as the pattern only replaces the first occurrence. – Mike Samuel Jan 24 '12 at 14:26

5 Answers5

5

You can use this:

    var str = "How are you doing?";
    var replace = new Array(" ", "[\?]", "\!", "\%", "\&");
    var by = new Array("-", "", "", "", "and");
    for (var i=0; i<replace.length; i++) {
        str = str.replace(new RegExp(replace[i], "g"), by[i]);
    }

Putting that into a function:

function str_replace(replace, by, str) {
    for (var i=0; i<replace.length; i++) {
        str = str.replace(new RegExp(replace[i], "g"), by[i]);
    }
    return str;
}

Usage example fiddle: http://jsfiddle.net/rtLKr/

Rick Kuipers
  • 6,616
  • 2
  • 17
  • 37
  • Well it's based on regular expressions, so yes most of them do need wrapping and escaping. I'm usually too lazy to actually think about it and just throw it into trial and error on jsFiddle.net or something. – Rick Kuipers Jan 24 '12 at 14:24
3

Beauty of JavaScript is that you can extend the functionality of base types so you can add a method to String itself:

// v --> array of finds
// s --> array of replaces
String.prototype.replaceAll = function(v, s){
    var i , ret = this;
    for(i=0;i<v.length;i++)
        ret = ret.replace(v[i], s[i]);
    return ret;
}

and now use it:

alert("a b c d e f".replaceAll(["a", "b"], ["1", "2"])); //replaces a b with 1 2

Demo is here.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
2

If it's easier for you, you might fancy something like this;

str.replace(/[ab]/g, function (match, i) {
    switch (match) {
        case "a":
          return "A";
        case "b":
            return "B";    
    }
}));

i.e. make a regular expression in parameter 1 which accepts all the tokens you're looking for, and then in the function add cases to do the replacement.

Matt
  • 74,352
  • 26
  • 153
  • 180
2

Here's a mix of some of the other answers. I just like it, because of the key-value declaration of replacements

function sanitize(str, replacements) {
    var find;
    for( find in replacements ) {
        if( !replacements.hasOwnProperty(find) ) continue;
        str = str.replace(new RegExp(find, 'g'), replacements[find]);
    }
    return str;
}

var test = "Odds & ends";
var replacements = {
    " ": "-", // replace space with dash
    "&": ","  // replace ampersand with comma
    // add more pairs here
};

cleanStr = sanitize(str, replacements);
Flambino
  • 18,507
  • 2
  • 39
  • 58
0

PHP.js has a function that could fix your issue : http://phpjs.org/functions/str_replace:527

David Laberge
  • 15,435
  • 14
  • 53
  • 83