3

I have a string of text here that will be dynamically generated to be one of the following:

<h1 id="headline">"Get your FREE toothbrush!"</h1>

OR

<h1 id="headline">"FREE floss set and dentures!"</h1>

Since this will be dynamically generated I won't be able to wrap a <span> around the word "FREE" so I want to specifically target the word "FREE" using Javascript so that I can style it with a different font-family and font-color than whatever styling the <h1> is set to. What methods do I use to go about doing this?

Marc R
  • 31
  • 1
  • 3
  • 2
    Does this answer your question? [How to highlight text using javascript](https://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript) – Heretic Monkey Nov 03 '20 at 23:13

4 Answers4

6

You can search and replace the substring 'FREE' with styled HTML. If 'FREE' occurs more than once in the string you may need to use regex (unless you don't need to support Internet Explorer). See How to replace all occurrences of a string?

In your case:

let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>'
str = str.replace(/FREE/g, '<span color="red">FREE</span>');
jla
  • 4,191
  • 3
  • 27
  • 44
  • 3
    A simple improvement with regex for a word is \bWORD\b – user2864740 Nov 03 '20 at 23:19
  • @user2864740 Correct me if I'm wrong, but isn't `\bWORD\b` just a conciser way to write `(?<=(^|\s+))FREE(?=($|\s+))`? Doesn't `\b` target word boundaries? – shreyasm-dev Nov 03 '20 at 23:23
  • \b does target word boundaries. It’s not the same though, as the alternate \s form shown would (only) match a space while \bWORD\b would break on a - or ., eg. Compare with the input: “Foo-WORD!”. It comes down to the precise behavior that is desired.. – user2864740 Nov 04 '20 at 04:35
1

The property you are looking for is innerHTML, look the following example:

var word = document.getElementById('word');

function changeWord(){
    word.innerHTML = "another";
  word.style.backgroundColor = 'black';
  word.style.color = 'white';
}
<h1 id="headline">
  <span id="word">some</span> base title
</h1>

<button onClick="changeWord()">
  change
</button>
Rod Ramírez
  • 1,138
  • 11
  • 22
1

Here is a working example using slice and some classic concatenation.

EDIT: Code for the second string is also included now.

//get headline by id
var headline = document.getElementById("headline");

//declare your possible strings in vars
var string1 = "Get your FREE toothbrush!"
var string2 = "FREE floss set and dentures!"

//declare formatted span with "FREE" in var
var formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"

//target positions for the rest of your string
var string1Position = 13
var string2Position = 4

//concat your vars into expected positions for each string
var newString1 = string1.slice(0, 9) + formattedFree + string1.slice(string1Position);
var newString2 = formattedFree + string2.slice(string2Position)


//check if strings exist in html, if they do then append the new strings with formatted span
if (headline.innerHTML.includes(string1)) {
  headline.innerHTML = newString1 
}
else if (headline.innerHTML.includes(string2)) {
  headline.innerHTML = newString2
}
<!-- As you can see the original string does not have "FREE" formatted -->
<!-- Change this to your other string "FREE floss set and dentures!" to see it work there as well -->
<h1 id="headline">Get your FREE toothbrush!</h1>
Aib Syed
  • 3,118
  • 2
  • 19
  • 30
0

You can split the text and convert the keyword "FREE" to a span element. So you can style the keyword "FREE". This method is safe because does not alter any non-text html element.

var keyword = "FREE";
var headline = document.getElementById("headline");
var highlight, index;
headline.childNodes.forEach(child => {
  if (child.nodeType == Node.TEXT_NODE) {
    while ((index = child.textContent.indexOf(keyword)) != -1) {
      highlight = child.splitText(index);
      child = highlight.splitText(keyword.length);
      with(headline.insertBefore(document.createElement("span"), highlight)) {
        appendChild(highlight);
        className = 'highlight';
      }
    }
  }
});
.highlight {
  /* style your keyword */
  background-color: yellow;
}
<div id="FREE">
  <h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1>
</div>
Naci Er
  • 1
  • 1