I tried this : Replace multiple strings at once And this : javascript replace globally with array how ever they are not working.
Can I do similar to this (its PHP):
$a = array('a','o','e');
$b = array('1','2','3');
str_replace($a,$b,'stackoverflow');
This result will be :
st1ck2v3rfl2w
I want to use regex at the same time. How can I do that ? Thank you.
replace(/cat/gi, "dog"); // now str = "I have a dog, a dog, and a goat." str = str. replace(/dog/gi, "goat"); // now str = "I have a goat, a goat, and a goat." str = str. replace(/goat/gi, "cat"); // now str = "I have a cat, a cat, and a cat."
Given a string and a pattern, replace multiple occurrences of a pattern by character 'X'. The conversion should be in-place and the solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single 'X'.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
var str = "I have a cat, a dog, and a goat.";
var mapObj = {
cat:"dog",
dog:"goat",
goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
return mapObj[matched];
});
Check fiddle
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