Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Multiple String at Once With Regex in Javascript

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.

like image 764
Ayro Avatar asked Dec 23 '13 12:12

Ayro


People also ask

How do I replace multiples in a string?

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

Which one is correct string function replace multiple occurrences in input string?

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

How do you replace all occurrences of a character in a string in Javascript?

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.


1 Answers

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

like image 98
Just code Avatar answered Nov 15 '22 16:11

Just code