gpt4 book ai didi

javascript - 从 html 字符串中删除样式

转载 作者:行者123 更新时间:2023-11-30 14:01:06 25 4
gpt4 key购买 nike

我有一个 HTML 字符串。它可以是任意数量的元素。我想删除任何包含字体大小的内联样式。

例如:

`<p><span style="font-size: 24px;">ORDER</span></p>`

我需要那个字体大小。我不太清楚如何使用 javascript 正则表达式执行此操作。我能得到一些帮助吗?

最佳答案

编辑:

revo 所述:

You're using JS. A language that leverages DOM.

那么,为什么不利用它呢?

ANY occurrence of inline styles containing font-size should be removed

var myString = `
<p>
<span style="font-size: 24px;">ORDER</span>
<span style="color:blue">
<b style="line-index:5px; font-size: 12px; margin: 5px">something</b>
</span>
</p>
`;
var divElement = document.createElement('div');
divElement.innerHTML = myString;

// loop through ALL DOM elements insidie the divElement
var elements = divElement.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
// remove the style attribute enterily if it contains font-size property
if ((elements[i].getAttribute('style') || '').includes('font-size')) {
elements[i].removeAttribute('style');
}
}

// here is your font-size free string
console.log(divElement.innerHTML)


如果我们只想得到字体大小的数字,那么我们可以从这个表达式开始:

(?:font-size:\s+)([0-9]+)(?:.+?")

在这里,我们在非捕获组中添加 (?:font-size:\s+) 作为左边界,然后我们收集我们想要的数字 ([0-9 ]+),然后使用另一个非捕获组 (?:.+?") 向上滑动到第一个 "

如果我们想要其他输出,我们可以简单地修改/更改这三个捕获和非捕获组。

DEMO

const regex = /(?:font-size:\s+)([0-9]+)(?:.+?")/gm;
const str = `"<div style="color: red;"><p style="font-size: 12px">Stuff</p></div>"`;
let m;

while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

enter image description here


如果我们想删除样式标签及其中的所有内容,这个表达式可能会起作用:

(style=".+?")

DEMO

const regex = /(style=".+?")/gm;
const str = `"<div style="color: red;"><p style="font-size: 12px">Stuff</p></div>""<div style="color: red;"><p style="font-size: 12px">Stuff</p></div>""<div style="color: red;"><p style="font-size: 12px">Stuff</p></div>""<div style="color: red;"><p style="font-size: 12px">Stuff</p></div>"`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

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

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