0

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

Monasha
7052 gold badges16 silver badges28 bronze badges
asked Nov 8, 2016 at 4:06
2

2 Answers 2

1

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))

answered Nov 8, 2016 at 4:15
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

function highlightMatch(originalValue, matchString) {
 var re = new RegExp(matchString, "igm");
 var replace = '<span class="highlighted">'+matchString+'</span>';
 return originalValue.replace(re ,replace);
}
answered Nov 8, 2016 at 4:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.