正则表达式:将HTML转换为JSON格式

时间:2018-04-27 11:02:45

标签: javascript html json regex

如何创建以下对象:

{
   element: "div",
   class: ["OneClass", "TwoClass"],
   text: "This is some text"
}

来自以下HTML:

<div class="OneClass TwoClass">This is some text</div>

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方式:

&#13;
&#13;
var el = document.querySelector('div');
var obj = {};
var clsList = el.classList.value.split(' ')
obj.element = el.tagName.toLowerCase();
obj.class = clsList;
obj.text = el.textContent
console.log(obj);
&#13;
<div class="OneClass TwoClass">This is some text</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用jQuery:

var html = '<div class="OneClass TwoClass">This is some text</div>';
var el = $(html);
var obj = {
  class: el.attr("class").split(/ /),
  text: el.text(),
  element: el.prop("tagName")
};
console.log(JSON.stringify(obj));

输出:

{"class":["OneClass","TwoClass"],"text":"This is some text","element":"DIV"}