如何在html标签中包装未包装的字符串?

时间:2017-12-16 19:14:55

标签: javascript html

// From
var first = 'Text here <code>var first = "first";</code> Another text 
<code>var second = "second";</code>'
// To 
var second =  '<p>Text here</p> <code>var first = "first";</code> 
<p>Another text</p> <code>var second = "second";</code>'

我收到一个像“From”这样的字符串,我需要解析它到第二个例子,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

创建一个元素,将该字符串放入元素中,然后迭代子节点并用包含相关文本的新<p>替换文本节点。然后最终得到结果html

&#13;
&#13;
// From
var first = `Text here <code>var first = "first";</code> Another text 
<code>var second = "second";</code>`


var div = document.createElement('div');
div.innerHTML = first;

var nodes = div.childNodes;

for (var i = 0; i < nodes.length; i++) {
  if (nodes[i].nodeType == 3) {
    var p = document.createElement('p');
    p.textContent = nodes[i].textContent;
    div.replaceChild(p, nodes[i])
  }
}

let res = div.innerHTML;

console.log(res)
&#13;
&#13;
&#13;