简体   繁体   中英

Replacing certain characters in javascript

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?

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/

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 .

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

ie 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.

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

PHP.js有一个可以修复你的问题的函数: http ://phpjs.org/functions/str_replace:527

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM