gpt4 book ai didi

javascript - 从 HTML 字符串中提取样式

转载 作者:行者123 更新时间:2023-12-04 13:28:06 24 4
gpt4 key购买 nike

所以我有一个表示 DIV innerHTML 的字符串,我想将所有样式从跨度提取到一个数组。以下是示例字符串:

string1 = <span style="background-color: #808080">U posljednji čas. 123</span>
string2 = <span style="background-color: #808080">U <span style="font-style: italic">posljednji</span> čas. 123</span>
我希望输出看起来像这样:
string1output1 = ['background-color: #808080']
string1output2 = ['background-color: #808080', 'font-style: italic']
或者:
string2output1 = ['<span style="background-color: #808080">']
string2output2 = ['<span style="background-color: #808080">', '<span style="font-style: italic">']
考虑到字符串内的样式可能超过 1 个跨度,最简单和最有效的方法是什么?另外我需要用一些东西替换跨度,所以第二种方法会更容易,因为我可以用数组中的项目调用替换字符串。
谢谢你的帮助

最佳答案

正如其他人所提到的,您可以解析字符串并从中获取样式属性信息。
如果 1 个元素包含多于 1 个样式,我不确定是否要拆分样式,但下面的示例默认情况下确实考虑了这一点。但是,正如您在第四个示例中看到的那样,可以通过第二个函数参数关闭它。
所以步骤是:

  • 将字符串解析为 DOM
  • 遍历所有包含样式的元素
  • 将找到的样式添加到返回数组(在 ; 上拆分值,除非参数 split 设置为 false)

  • string1 = '<span style="background-color: #808080">U posljednji čas. 123</span>';
    string2 = '<span style="background-color: #808080">U <span style="font-style: italic">posljednji</span> čas. 123</span>';
    string3 = '<span style="background-color: #808080;font-style: italic">U posljednji čas. 123</span>';

    console.log(stringToStyleArray(string1));
    console.log(stringToStyleArray(string2));
    console.log(stringToStyleArray(string3));
    console.log(stringToStyleArray(string3, false));

    function stringToStyleArray(string, split = true) {
    let styles = [];
    dom = (new DOMParser()).parseFromString(string, "text/html");
    dom.querySelectorAll('[style]').forEach((el) => {
    if(split) {
    styles = [...styles, ...el.getAttribute("style").split(';')];
    }
    else {
    styles.push(el.getAttribute("style"));
    }
    });
    return styles;
    }

    关于javascript - 从 HTML 字符串中提取样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66870329/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com