skip to Main Content

I have a string containing html that is outputted from Wix Studio. I am trying to manipulate and put back within the original tags. So far I have managed to strip the tags and manipulate the string (wrapping each letter in a ), but I can’t figure out how to put the manipulated string (inner) back within the original tags, desired outcome below. Won’t always be <h1>, could be <h2> through to <h6>, potentially a <p> – Unable to use jQuery!

// Get string from Wix using the Wix Editor Elements ($w) APIs)
var html = $w('Text').html;

var string = html.replace(/(<([^>]+)>)/ig, ''), 
    wrap = string.replace(/w/g, "<span>$&</span>");

html returns "<h1 class="wixui-rich-text__text">Add a Title</h1>" ✅ All good

string returns "Add a Title" ✅ All good

wrap returns "<span>A</span><span>d</span><span>d</span> <span>a</span> <span>T</span><span>i</span><span>t</span><span>l</span><span>e</span>" ✅ All good

Desired result:

The original html tag with the modified content within:

output to return "<h1 class="wixui-rich-text__text"><span>A</span><span>d</span><span>d</span> <span>a</span> <span>T</span><span>i</span><span>t</span><span>l</span><span>e</span></h1>"

A bit out of my depth, may be a better way to go about.

Many thanks!

For ref: https://www.wix.com/velo/reference/$w/text/html

2

Answers


  1. a better way is to parse it as DOM and manipulate it

    const html = '<h1 class="wixui-rich-text__text">Add a Title</h1>';
    const fragment = new DocumentFragment();
    const wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    fragment.append(wrapper);
    const el = fragment.firstChild.firstChild;
    const content = el.innerHTML;
    el.innerHTML = content.split('').map(c => `<span>${c}</span>`).join('');
    const modifiedHtml = el.outerHTML;
    console.log(modifiedHtml);
    Login or Signup to reply.
  2. I think this will suit your needs:

    html.replace(/(?<=(<([^>]+)>[^<>]*))w/ig, '<span>$&</span>');
    

    Test Input string:

    <div><h1 class="wixui-rich-text__text">Add a Title</h1><p>Test <b>Again</b></p></div>
    

    Output String:

    <div><h1 class="wixui-rich-text__text"><span>A</span><span>d</span><span>d</span> <span>a</span> <span>T</span><span>i</span><span>t</span><span>l</span><span>e</span></h1><p><span>T</span><span>e</span><span>s</span><span>t</span> <b><span>A</span><span>g</span><span>a</span><span>i</span><span>n</span></b></p></div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search