ews2001 ews2001 - 2 months ago 20
Javascript Question

Highlight word based on the word count in javascript

If I have the following string: "This is another song you should listen to"
I was trying to write a function to only highlight the word based on the word count. For example, I want to highlight the 4th word using a method like: highlightWord(originalString,nthWord). And the returned string would be:

"This is another <span class=\"highlighted\">song</span> you should listen to"

I tried using a highlightMatch function that I wrote, one by passing a search string (regexMatch = "is"), but the problem is that it highlights the is in "This" instead of "is":

function highlightMatch(originalValue,regexMatch) {
var tempInnerHTML = stripTags(originalValue);
originalValue.innerHTML = tempInnerHTML.replace(regexMatch,'<span class="highlighted">'+regexMatch+'</span>');

I also tried using this highlightNthWord method:

function highlightNthWord(string,n) {
var m = string.match(new RegExp('^(?:\\w+\\W+){' + n + '}(\\w+)'));
return m && '<b>'+m[1]+'</b>';

But this one just returns only the nth word highlighted, not the whole sentence with the nth word highlighted.
I'm hoping to stick with javascript only (no jquery).


You can split the string be space and then build the string back:

function highlightNthWord(string,n) {
  var m = string.split(new RegExp(/\s+/));
  return m.splice(0, n-1).join(" ") + (' <b>'+m.splice(0, 1)+'</b> ') + m.join(" ");
console.log(highlightNthWord('This is another song you should listen to', 4))