将跨度字符串分成跨度数组

时间:2017-07-06 04:33:37

标签: html regex split

我有一个包含在跨度中的文本块,我需要将其拆分为数组。

所以目前我有

var s = `
   <span class="hoverable">c</span>
   <span class="hoverable">o</span>
   <span class="not-hoverable">o</span>`;

我需要

var s = [
   "<span class="hoverable">c</span>",
   "<span class="hoverable">o</span>",
   "<span class="not-hoverable">o</span>"];

我已尝试s.split(/<\/?span>/);分割<span>和结算</span>的会计但

var s = [
  "<span class="hoverable">c", 
  "<span class="hoverable">o", 
  "<span class="not-hoverable">o",...]

所以它不包括收盘时间。

2 个答案:

答案 0 :(得分:3)

与正常情况一样,当正则表达式问题徘徊到HTML或XML领域时,我建议regexp不是正确的工具。使用您正在使用的语言提供的正确HTML解析器。如果是JavaScript(使用var和字符串模板语法暗示):

let s = `
   <span class="hoverable">c</span>
   <span class="hoverable">o</span>
   <span class="not-hoverable">o</span>`;
let d = document.createElement('div');
d.innerHTML = s;
let result = Array.from(d.children).map(e => e.outerHTML);
console.log(result);

答案 1 :(得分:0)

如果您在浏览器中工作并且值在元素内,则始终可以使用DOM。如果不是,并且您有一个字符串,那么您仍然可以动态使用DOM。最后,您可以使用正则表达式。

这是一个回合:

&#13;
&#13;
var s = ' ' +
  '<span class="hoverable">c</span>' +
  '<span class="hoverable">o</span>' +
  '<span class="not-hoverable">o</span> ';
var r2 = s.match(/<span(.*?)>(.*?)<\/span>/gm);
console.log("using regular expressions");
console.log(r2);

function findWithDOM() {
  console.log("using DOM");
  var elements = [].slice.call(document.querySelectorAll('#myDiv span'));
  console.log(elements);
}

function findWithDynamicDOM() {
  console.log("using Dynamic DOM");
  var element = document.createElement("div");
  element.innerHTML=s;
  var elements = [].slice.call(element.querySelectorAll('span'));
  console.log(elements);
}
&#13;
<div id="myDiv"><span class="hoverable">c</span>
  <span class="hoverable">o</span>
  <span class="not-hoverable">o</span>
</div>
<input id='btnFind' onclick='findWithDOM()' value='Find With DOM' type="button" />
<input id='btnFind' onclick='findWithDynamicDOM()' value='Find Dynamic DOM' type="button" />
&#13;
&#13;
&#13;