gpt4 book ai didi

javascript - 正则表达式:必须存在的组,但事先未知它将在哪里

转载 作者:行者123 更新时间:2023-11-28 14:15:43 26 4
gpt4 key购买 nike

我需要获取href参数值,但仅适用于 <link>具有 type='image/x-icon' 的标签属性(换句话说,favicon 标签):

// Below ones must be parsed
<link rel="icon" type="image/x-icon" href="#" />
<link rel="shortcut icon" type="image/x-icon" href="#" />

// Below ones must be ignored
<link rel="stylesheet" href="styles.html">
<link rel="search" href="search.html">
<link rel="help" href="help.html">

问题是type="image/x-icon"可能在href="#"之前或之后,但正是这些情况之一。我如何用 JavaScript 的正则表达式来表达它?

🔗 Regex fiddle with my try

最佳答案

您可以使用DOMParser API 替代

let str = `
<link rel="icon" type="image/x-icon" href="#" />
<link rel="shortcut icon" type="image/x-icon" href="#" />


<link rel="stylesheet" href="styles.html">
<link rel="search" href="search.html">
<link rel="help" href="help.html">`

let parser = new DOMParser()
let parsed = parser.parseFromString(str,"text/html")

let links = parsed.getElementsByTagName('link')

console.log(Object.values(links).filter(val=> val.type === 'image/x-icon'))

关于javascript - 正则表达式:必须存在的组,但事先未知它将在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565759/

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