【问题标题】:how to pass from string to object in javascript如何在javascript中从字符串传递到对象
【发布时间】:2021-07-09 02:51:53
【问题描述】:

我在 javascript 中有以下代码。

var abc = `<div class="hello" data-id="99" data-price="100" data-category="mal">
        <div class="hello-category">Hello word</div>
        <div class="hello-description"><h2>The best burger in town 12345615</h2></div>
        </div>`;

我想得到以下结果:

<div class="hello" data-id="99" data-price="100" data-category="mal">

【问题讨论】:

    标签: javascript regex string object split


    【解决方案1】:

    您可以使用DOMParser

    var abc = `<div class="hello" data-id="99" data-price="100" data-category="mal"><div class="hello-category">Hello word</div><div class="hello-description"><h2>The best burger in town 12345615</h2></div>`;
    const parser = new DOMParser().parseFromString(abc, "text/html");
    parser.body.firstChild.innerHTML=''; //<-- remove innerhtml of the div
    const result = parser.body.innerHTML; //<-- get result
    console.log(result);

    【讨论】:

      【解决方案2】:

      您可以将其转换为 DOM 节点,然后对其执行 DOM 操作,如下所示

      const abc_string = `<div class="hello" data-id="99" data-price="100" data-category="mal">
              <div class="hello-category">Hello word</div>
              <div class="hello-description"><h2>The best burger in town 12345615</h2></div>
              </div>`;
      
      //  convert string to DOM node
      const abc_node = new DOMParser().parseFromString(abc_string, 'text/html').body.firstChild;
      
      //  iterate over child nodes, removing them each time
      Array.from( abc_node.childNodes ).forEach(thisChild => {
         abc_node.removeChild( thisChild );
      });
      
      //  what you have left
      console.log(abc_node);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2021-05-05
        • 2015-10-10
        相关资源
        最近更新 更多