I'm struggling with a seemingly simple task, and I feel quite embarrassed that I can't seem to solve it. My goal is to identify words in a string that begin with '@' or '#' and change their color to blue. The string itself comes from an API, so initially setting the word inside a span is not an option.
I attempted using the string method `replace()` with a regular expression to locate words starting with '@', and then replacing them with a span containing the same text colored blue. Although I've come across this solution multiple times on Stack Overflow, implementing it causes the entire span to render as text instead of just the content itself. Additionally, the font color remains unchanged – resulting in
<span style='color: blue;'>@user42</span>
being displayed rather than simply @user42
.
While trying a different regex pattern to prevent spans from appearing as text on the page, it feels like I'm missing something crucial and performing unnecessary steps to address an unknown issue.
Here's my attempt at resolving this without using `.replace()`, but I'm struggling to place the newly created span back in the original position where the word was 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';
}
});
Could someone guide me on utilizing `replace()` effectively to identify words starting with '@' or '#' and replace them with the same text in a different color?