【问题标题】:regex to extract attribute from html as text [closed]正则表达式从html中提取属性作为文本[关闭]
【发布时间】:2020-04-05 18:01:05
【问题描述】:

我从我的 api 收到以下响应作为字符串

var responseText = '<ol><li> <a href="abc.com"></a></li><li> <a href="xyz.com"></a></li></ol>'

现在我只想从字符串中提取 href 值,所以我正在考虑编写一个正则表达式来检查获取它...

我的正则表达式太弱了

我只想要 [abc.com, xyz.com] 作为我的输出

提前致谢

【问题讨论】:

标签: javascript regex


【解决方案1】:

你可以比正则表达式做得更好。您可以创建一个元素,将您的响应用作其内部 HTML,然后提取所有 href

const container = document.createElement('div');
container.innerHTML = responseText;
const hrefs = [...container.querySelectorAll('[href]')].map(element => element.getAttribute('href'));

console.log(hrefs); // ['abc.com', 'xyz.com']

【讨论】:

    【解决方案2】:

    这里不需要RegEx。只需将字符串转成解析后的 H​​TML,然后使用 DOM API 提取属性值即可:

    var responseText = '<ol><li> <a href="abc.com"></a></li><li> <a href="xyz.com"></a></li></ol>';
    
    let temp = document.createElement("div"); // Temporary container
    temp.innerHTML = responseText;            // Populate with parsed HTML string
    
    // Collect all the <a> elements into an array
    let anchors = Array.prototype.slice.call(temp.querySelectorAll("a")); 
    
    // Loop over the collection of anchors
    let results = anchors.map(function(a){
       return a.getAttribute("href"); // Push the href attribute value into the results array
      //return a.href;                // Grab the href property value.
    });
    
    console.log(results);

    【讨论】:

    • 请记住a.href 将返回绝对的href,因此对于无效的hrefs 它将假定它是一个相对路径。正因为如此,我更新了我的答案。在这种情况下,a.getAttribute('href') 是要走的路。
    • @RoboRobok 正在更新您评论的答案。
    • 另外,您不需要Array.prototype.slice.call。有Array.from() 方法,当然还有传播语法。
    • @RoboRobok 其实你可以。在某些浏览器中从querySelectorAll() 返回的节点列表不支持.map,并且这些相同的浏览器也不支持Array.from 或传播语法,因此您必须使用某些东西来转换所有浏览器都支持的节点列表.
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多