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?