1

var str = "~lorem ~lorem1 ~ipsum ~ipsum2 ~dolor ~dolor3";
str = str.replace(/~lorem/g, 'a');
str = str.replace(/~ipsum/g, 'b');
str = str.replace(/~dolor/g, 'c');
console.log(str);  // a a1 b b2 c c3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to execute all str.replace at once?

qadenza
  • 8,611
  • 18
  • 61
  • 108

2 Answers2

1

You could take an object and build a regular expression from the keys.

To replace with the values, you need a function which take the found string and gets the value from the object.

If the strings contains special characters, you need to escape them as well.

var str = "~lorem ~lorem1 ~ipsum ~ipsum2 ~dolor ~dolor3",
    values = { '~lorem': 'a', '~ipsum': 'b', '~dolor': 'c' };

str = str.replace(new RegExp(Object.keys(values).join('|'), 'g'), k => values[k]);

console.log(str);  // a a1 b b2 c c3
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

You can combine you regex like this:

/(~lorem)|(~ipsum)|(~dolor)/g

then you need to use a function as the second parameter to replace to set 'a','b', and 'c' as the replacement for the found text

ControlAltDel
  • 32,042
  • 9
  • 48
  • 75