Replace a word in a string with a styled span dynamically

Viewed 122

I'm trying to do something pretty simple, but I'm embarrassed to say that I can't figure it out. I'm looking to find words in a string that start with '@' or '#' and give the word a styling color of blue. The string is coming from an API, so I can't initially set the word inside a span.

I've tried used string replace() with a regular expression to find words that start with '@', and replace it with a span that has the same text, but with the color blue. I've seen this answer pop up throughout SO, but when I try to implement it the entire span is rendered as text, instead of just the text itself. Moreover, the text doesn't have the color changed to blue– I'm getting <span style='color: blue;'>@user42</span> as text, instead of just @user42.

I used a different regexp to remove the spans from being rendered to the page as text but that just seems like I missing something and doing extra work to remedy what I'm unaware of.

Here's what I've tried to do to solve it without using .replace(), but I'm unable to insert the newly created span into the same position as the word being removed.

tweetText[0].split(' ').forEach((word) => {
  if (word.innerText.startsWith('@') || word.innerText.startsWith('#')) {
     const span = document.createElement('span');
     span.innerText = word;
     span.style.color = 'blue';
   }
 });

How can I use replace() to find a word that starts with '@' or '#' and replace it with the same text, but with a different color?

1 Answers

Added color, background-color, padding, and border-radius to look good.

const result = document.querySelector(".result");

function colorizeSelectedText(str) {
  const result = str
    .split(" ")
    .map((word) => {
      if (word.startsWith("@") || word.startsWith("#")) {
        return `<span style='color: blue; background: bisque; padding: 0.25rem; border-radius: 4px;'>${word}</span>`;
      }
      return word;
    })
    .join(" ");
  return result;
}

const text = colorizeSelectedText(
  "This is @test for the #color that is not colored"
);

result.innerHTML = text;
<div class="result"></div>

Related