3

I've searched but cannot adapt anything to my code. I'm trying to make var toReplace = "warming" into an array var toReplace = ['global', 'warming'] so it will replace every word from the array in input with var newWord which just wraps the word in a span. thanks for any help!

if (temperature > 90) {
    var input = 'ITS GLOBAL EFFING WARMING';
    var toReplace = "WARMING";
    var emphasisColor = 'cyan';
};

var newWord = `<span style="color: ${emphasisColor}">${toReplace}</span>`;
var regEx = new RegExp(toReplace,"g");
var output = input.replace(regEx, newWord);
user18815
  • 55
  • 5

2 Answers2

6

join by | to alternate, so that either word in the array will match. Also make sure to use the i flag to make it case-insensitive.

Also put $& in the replacement string to echo the matched string (so that, for example, when GLOBAL is matched, the result is <span style="color: cyan">GLOBAL</span> rather than <span style="color: cyan">global,warming</span>:

var input = 'ITS GLOBAL EFFING WARMING';
var toReplace = ['global', 'warming']
var emphasisColor = 'cyan';

var regEx = new RegExp(toReplace.join('|'),"gi");
var output = input.replace(regEx, `<span style="color: ${emphasisColor}">$&</span>`);
console.log(output);

Of course, this depends on toReplace not having any special characters. If it can have more than just word characters, you might replace-escape them all first.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You could use a forEach to execute a function for each element in the array:

if (temperature > 90) {
    var input = "ITS GLOBAL EFFING WARMING";
    var toReplace = ["GLOBAL", "WARMING"];
    var emphasisColor = "cyan";
};
toReplace.forEach((element, index) => {
    regEx = new RegExp(element, "gi");
    input = input.replace(regEx, `<span style="color: ${emphasisColor}">${toReplace[index]}</span>`);
});

You can also use a for loop instead of forEach to obtain the same result.

Happy Coding! :)

Apogee
  • 109
  • 6