Replacing certain characters in javascript

Industrial picture Industrial · Jan 24, 2012 · Viewed 13.4k times · Source

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?

Answer

Rick Kuipers picture Rick Kuipers · Jan 24, 2012

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/