在html字符串中的两个标签之间替换文本- JavaScript RegEx?[关闭]

9njqaruj  于 2023-11-20  发布在  Java
关注(0)|答案(2)|浏览(122)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

13天前关门了。
Improve this question
我有一个包含从Wix Studio输出的html的字符串。我试图操作并放回原始标签中。到目前为止,我已经设法剥离标签并操作字符串(将每个字母用a Package 起来),但我不知道如何将被操纵的字符串(内部)放回原始标记中,下面是预期的结果。不会总是<h1>,可能是<h2><h6>,可能是<p>-无法使用jQuery!

  1. // Get string from Wix using the Wix Editor Elements ($w) APIs)
  2. var html = $w('Text').html;
  3. var string = html.replace(/(<([^>]+)>)/ig, ''),
  4. 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

zwghvu4y

zwghvu4y1#

我认为这将满足您的需求:

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

字符串
测试输入字符串:

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


输出字符串:

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

nxagd54h

nxagd54h2#

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

  1. const html = '<h1 class="wixui-rich-text__text">Add a Title</h1>';
  2. const fragment = new DocumentFragment();
  3. const wrapper = document.createElement('div');
  4. wrapper.innerHTML = html;
  5. fragment.append(wrapper);
  6. const el = fragment.firstChild.firstChild;
  7. const content = el.innerHTML;
  8. el.innerHTML = content.split('').map(c => `<span>${c}</span>`).join('');
  9. const modifiedHtml = el.outerHTML;
  10. console.log(modifiedHtml);

字符串

相关问题