[英]Remove a style from an html string
我有一个HTML字符串。 它可以是任意数量的元素。 我想删除任何包含字体大小的内联样式。
例如:
`<p><span style="font-size: 24px;">ORDER</span></p>`
我需要那种字体大小。 我不太清楚如何使用javascript正则表达式执行此操作。 我可以帮忙吗?
编辑:
如revo所述:
您正在使用JS。 一种利用DOM的语言。
那么,为什么不利用它呢?
任何出现的包含字体大小的内联样式都应删除
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]+)
并且向上滑动到第一"
使用另一非捕获组(?:.+?")
。
如果我们希望有其他输出,我们可以简单地修改/更改这三个捕获和非捕获组。
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}`); }); }
如果我们要删除样式标签及其中的所有内容,则此表达式可能会起作用:
(style=".+?")
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);
在这里,您可以使用此正则表达式执行此操作。
找
(<[\w:]+)(?=((?:[^>"']|"[^"]*"|'[^']*')*?\s)\s*style\s*=\s*(?:(['"])\s*font-size:(?:(?!\3)[\S\s])*\3)\s*((?:[^>"']|"[^"]*"|'[^']*')*?>))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>
更换
$1$2$4
https://regex101.com/r/4LC6R0/1
正则表达式与评论
( < [\w:]+ ) # (1), Any tag
(?= # Assert (a pseudo atomic group)
( # (2 start), Before style
(?: [^>"'] | " [^"]* " | ' [^']* ' )*?
\s
) # (2 end)
\s* style \s* = \s* # Style attribute
(?:
( ['"] ) # (3), Quote
\s* font-size: # Containing font-size:
(?:
(?! \3 )
[\S\s]
)*
\3
)
\s*
( # (4 start), After style
(?: [^>"'] | " [^"]* " | ' [^']* ' )*?
>
) # (4 end)
)
# Have everything just consume the rest of the tag
\s+
(?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.