0

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 class="title">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 class="title">Lorem ipsum dolor sit amet</h1>

<!-- after -->
<h1 class="title"><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?

1
  • Where you extract the words make sure you store the remainder as well, then stitch them back in at the end. Commented May 13, 2022 at 17:48

1 Answer 1

1

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 class="title">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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.