1

I'm needing to wrap all of the characters within a string inside of their own tag. I've been able to do that with the following:

$(".text").html(function(index, html) {
   return html.replace(/(\w)/g, "<span>$&</span>");
});

This works, but I need it to also ignore any HTML tags. For example, this string:

'Text here<br>Text Here'

Currently it's ignoring the <>, but wrapping the "b" and "r" with span tags. Is it possible to ignore the entire html tag?

Thomas Spade
  • 724
  • 6
  • 11
  • 25

1 Answers1

1

You have a DOM parser literally at your fingertips, yet instead you choose regex...

Doing it without jQuery because why do you even need jQuery for this?

function wrapEachLetter(textNode) {
    // Now you have only text, guaranteed!
    const html = "<span>"+textNode.nodeValue.split("").join("</span><span>")+"</span>";
    const tmp = document.createElement('ins');
    tmp.innerHTML = html;
    while(tmp.firstChild) textNode.parentNode.insertBefore(tmp.firstChild, textNode);
    textNode.remove();
}
document.querySelectorAll(".text").forEach(function recurse(root) {
    node.childNodes.forEach(node=>{
        switch( node.nodeType) {
        case Node.TEXT_NODE:
            wrapEachLetter(node);
            break;
        case Node.ELEMENT_NODE:
            recurse(node);
            break;
        // leave any other node types as-is
        }
    });
});
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592