【问题标题】:Combined two HTML data value with Regex将两个 HTML 数据值与 Regex 结合
【发布时间】:2019-07-31 07:59:30
【问题描述】:

我正在尝试将两个 HTML 数据合并到一个 HTML 标记中。我正在尝试使用正则表达式。

HTML 是这样的

var temp = document.getElementById('data').innerHTML;


console.log(temp);
<div id="data">
  <strong>20 </strong>
  <strong>0 </strong>
  <strong>0 /-</strong>
</div>

我的输出是&lt;strong&gt;2000/-&lt;/strong&gt;

【问题讨论】:

  • 中间的零怎么了?
  • 从元素中获取文本并将它们连接起来。为什么要使用正则表达式
  • 这是一个动态数据,我得到了上面描述的值。但这应该与正则表达式结合使用。
  • 你可以得到document.getElementById('data').innerText 并用空字符串替换所有空格
  • 使用正则表达式来获取在HTML字符串中完成的内容可以将其与O҉peni͏ng͏͏̷̷t͘͜h͏̴̨e̷̷͟͟͟͞҉̸̸̸̢̧͟͟ţ̵̵̢̢̕͢҉ò̵̸̢̢͔̫̺͠ọ̘̜̻̰͔̯͙͔̯͙͔̯͙͔̯͙͔̯͙͘͘͘͘͘͠͠͠͠͠... @ 987654321修复 HTML 输出而不是做这个 shizzle。

标签: javascript html regex


【解决方案1】:

// you should get the textContent instead of the innerHTML
var temp = document.getElementById('data').textContent;

// removes all spaces and 
// surrounds the output with the <strong> element
var newhtml = `<strong>${ temp.replace(/\s/g,'') }</strong>`;

// replaces the innerHTML of the data with newhtml 
document.getElementById('data').innerHTML = newhtml
<div id="data">
  <strong>20 </strong>
  <strong>0 </strong>
  <strong>0 /-</strong>
</div>

【讨论】:

    【解决方案2】:

    你不需要正则表达式,你可以简单地用

    连接字符串

    str.concat(string2, string3, string4, etc)

    并给所有强标签一个单独的 ID

    但是,如果内容是动态的并且没有硬编码,您可以遍历 document.getElementById('data') 的子节点并获取每个子节点的 textContent 并以这种方式连接它们。

    【讨论】:

    • Mozilla 不鼓励使用 concat 方法,请参阅 this 帖子及其副本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2020-11-02
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多