解析String以获取数组

时间:2016-10-17 06:50:16

标签: javascript regex string parsing

现在我有一个看起来像的字符串。

const string = "<h1>Text<widget some-some-type='Some' data-some-id='ryteCAX4kaXFWmpuj'></widget><widget some-some-type='HtmlColumns' data-some-id='cw7gtkTqE49NarsS9'></widget></h1>"

我想知道如何在data-some-id='ryteCAX4kaXFWmpuj'内获取文字,只需获取ryteCAX4kaXFWmpuj

注意字符串

上可能有超过100个data-some-id

1 个答案:

答案 0 :(得分:1)

使用DOMParser解析HTML字符串。

// craete an instance of parser
var parser = new DOMParser();
const string = "<h1>Text<widget some-some-type='Some' data-some-id='ryteCAX4kaXFWmpuj'></widget><widget some-some-type='HtmlColumns' data-some-id='cw7gtkTqE49NarsS9'></widget></h1>"
  // parse the string to convert iti into dom
var doc = parser.parseFromString(string, "text/html");

// get all widget and convert NodeList to array 
// for iterating over them. You can even use Array.from()
// method in latest browsers
[].slice.call(doc.querySelectorAll('widget'))
  // iterate over them 
  .forEach(function(ele) {
    //  get data-* attribute value
    console.log(ele.dataset.someId)
  })

或者使用document.createElement创建一个包含HTML内容的元素并获取内部元素。

// create a div element
var div = document.createElement('div');
const string = "<h1>Text<widget some-some-type='Some' data-some-id='ryteCAX4kaXFWmpuj'></widget><widget some-some-type='HtmlColumns' data-some-id='cw7gtkTqE49NarsS9'></widget></h1>"
// set the html content of the div
div.innerHTML = string;

// get all widget and convert NodeList to array 
// for iterating over them. You can even use Array.from()
// method in latest browsers
[].slice.call(div.querySelectorAll('widget'))
  // iterate over them 
  .forEach(function(ele) {
    //  get data-* attribute value
    console.log(ele.dataset.someId)
  })