Skip to content
Advertisement

Change multiple words in the string (JS)

JS function finds a word in the string and encodes it as “highlight”.

But how can I change the multiple words to highlight instead of a single word?

For example;

highlightWord('test#word#covid');
highlightWord('test');

function highlightWord(word) {
  var word = word.split('#');
  var string = 'Hello world, test text';
  var newWord = '<span class="highlight">' + word + '</span>';

  // do replacement with regular expression
  var allWords = new RegExp('\b' + word + '\b', 'gi');
  var newString = string.replace(allWords, newWord);

  console.log(newString)
};

Before:

hello world, this is a word1, word2 and word3

After:

hello world, <span class='highligh'>word1</span>, <span class='highligh'>word2</span> and <span class='highligh'>word3</span>

Advertisement

Answer

My suggestion:

const highlightWord = s => s.split('#').map(s => `<span class="highlight">${s}</span>`);

console.log(highlightWord('test#word#covid'));
console.log(highlightWord('test'));

You’ve edited your question, I’ll update my answer:

var words = 'word1#word2#word3';
var string = 'hello world, this is a word1, word2 and word3';

words.split("#").map(w => {
  var regex = new RegExp('\b' + w + '\b', 'gi');
  string = string.replace(regex, `<span class="highlight">${w}</span>`);
});

console.log(string);
Advertisement