I need to extract some words from a string of text, insert every character of that words inside a span element and then replace the extracted words with the span elements. I have been able to convert characters into span elements but I can't figure out how to replace the extracted words with the span elements without deleting the other words.
<h1 >Lorem ipsum dolor sit amet</h1>
const title = document.querySelector('.title');
// Extract required words and split them into single character
const firstWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('L')).toString().split('');
const secondWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('a')).toString().split('');
// Return a new array with every character inside a span element
const spanCharacters = arr => {
return arr.map(char => {
const span = document.createElement('span');
span.textContent = char;
return span;
});
};
const spanFirstWord = spanCharacters(firstWord);
// return [<span>L</span>, <span>o</span>, <span>r</span>, <span>e</span>, <span>m</span>]
const spanSecondWord = spanCharacters(secondWord);
// return [<span>a</span>, <span>m</span>, <span>e</span>, <span>t</span>]
Now, what I'd like to do is this:
<!-- before -->
<h1 >Lorem ipsum dolor sit amet</h1>
<!-- after -->
<h1 ><span>L</span><span>o</span><span>r</span><span>e</span><span>m</span> ipsum dolor sit <span>a</span><span>m</span><span>e</span><span>t</span></h1>
How could I replace the extracted words with the generated spans keeping the other words where they are?
CodePudding user response:
Here is one way to do it:
const ttl=document.querySelector("h1.title"),
txt=ttl.textContent;
function spanifyWords(beginsArr,txt){
return txt.split(" ").map(w=>{
if (beginsArr.some(b=>w.startsWith(b)))
w="<span>" w.split("").join("</span><span>") "</span>";
return w
}).join(" ");
}
ttl.innerHTML=spanifyWords(["a","L"],txt);
span {color: green; border:1px solid red}
<h1 >Lorem ipsum dolor sit amet</h1>
Instead of . filter()
-ing I use .map()
to go through every word. Inside the callback function I check with .some()
relative to some beginsArr
whether the current word starts with one of the characters in question. If so, I "spanify" the word otherwise I return the word as is. At the end I stitch everything together again with .join()
.