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";
}
}));
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With