I’m trying to wrap specific words ("Ethan", "passionate", "UX/UI", and "Designer") in a span class in a paragraph for individual styling. However, since "Ethan" is followed directly by a comma in the HTML, the JavaScript only selects it if I include the comma ("Ethan,")—resulting in the comma being styled as well, which I don’t want. How can I apply the style only to "Ethan" without affecting the comma?
Here’s my current JS:
document.addEventListener('DOMContentLoaded', function() {
const herotext = document.getElementById('herotext');
const words = herotext.innerText.split(' ');
herotext.innerHTML = words.map(word => {
if (['Ethan', 'passionate', 'UX/UI', 'Designer'].includes(word))
{
return `<span style="color: #F33;">${word}</span>`;
} else {
return `<span>${word}</span>`;
}
});
});
And the HTML:
<h1 id="herotext">Hi, I’m Ethan, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
Thanks!
I’ve already tried wrapping the word "Ethan" in a <span> element and applying a specific CSS style to it, but this didn’t work. The issue is that in the HTML, "Ethan," appears as a single entity (with the comma directly after the name), preventing the span from targeting just "Ethan."
Here’s the HTML I used:
<h1 id="herotext">Hi, I’m <span class="highlight">Ethan</span>, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
And the CSS:
.highlight {
color: #333;
}
I know this is a very specific use case, but this is the only sentence I want to apply this algorithm to. Setting some rules around excluding commas from the styling seems like it would resolve the issue, I’m just not sure how to do this as I’m not a developer and have very very basic development knowledge – some help/a solution would be massively appreciated!
3
Answers
In your
map
, you can usereplace()
to clean up the words, as follows.And if you want to have space between your words, instead of commas, you can use
.join(' ')
on the arrayyou can apply the span styling to the specific words without affecting punctuation like THIS
You can split by the keywords, followed by space or comma (look-ahead regex of
(?=[, ])
, the regex beingnew RegExp(word + "(?=[, ])", 'g')
) and join back byword
being inserted into the template of your preference, looping the keyword array in the process.