替换 html 字符串中两个标签之间的文本 - Javascript RegEx?

问题描述 投票:0回答:1

我有一个包含从 Wix Studio 输出的 html 的字符串。我正在尝试操纵并放回原始标签内。到目前为止,我已经设法剥离标签并操纵字符串(将每个字母包装在 a 中),但我不知道如何将操纵的字符串(内部)放回原始标签内,下面是所需的结果。不会总是

<h1>
,可能是
<h2>
<h6>
,可能是
<p>
- 无法使用 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
退货
"<h1 class="wixui-rich-text__text">Add a Title</h1>"
✅一切都好

string
退货
"Add a Title"
✅一切都好

wrap
退货
"<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>"
✅一切都好

想要的结果:

修改后内容的原始html标签:

output
返回
"<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>"

有点超出我的深度,可能是更好的方法。

非常感谢!

供参考:https://www.wix.com/velo/reference/$w/text/html

javascript html regex tags velo
1个回答
0
投票

更好的方法是将其解析为 DOM 并对其进行操作

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

© www.soinside.com 2019 - 2024. All rights reserved.