Home > OS >  Replace text between two tags within html string - Javascript RegEx?
Replace text between two tags within html string - Javascript RegEx?

Time:11-05

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 >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 ><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

CodePudding user response:

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

const html = '<h1 >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);

CodePudding user response:

I think this will suit your needs:

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

Test Input string:

<div><h1 >Add a Title</h1><p>Test <b>Again</b></p></div>

Output String:

<div><h1 ><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>
  • Related