Home > Mobile >  How to iterate/loop over a text string that contains HTML tags while ignoring those HTML tags in Jav
How to iterate/loop over a text string that contains HTML tags while ignoring those HTML tags in Jav

Time:01-15

I have some dynamic copy text, a string, which contains some HTML tags used for line breaks and styling. E.g.: "This is a sample <b>piece of text</b> string".

I wish to iterate over the text so I can wrap each character in <span> </span> tags, in order to animate each character. However, I need to be able to ignore the HTML tags, like the <b></b> tags above so that any/all breaks or styles associated with those tags remains in place...?

I can run a simple, clean for of loop over the text string in order to wrap everything in span tags and then push that result to the div I want, see below:

textString = "This is a sample <b>piece of text</b> string."

for (let char of textString) {
    let span = document.createElement('span');
    span.textContent = char;
    let test = document.querySelector("#root");
    test.appendChild(span);
}

This will wrap EVERYTHING in that string in a span tag but then the tags are obviously shown on the screen - not what I need!

I know this regex: str.replace( /(<([^>] )>)/ig, ''); will remove all the HTML tags from the string but, as I said, I need the tags to actually remain in place for styling purposes?

Any help on this would be most appreciated...

  •  Tags:  
  • Related