gpt4 book ai didi

javascript - 如何在Javascript中获取字符串的href

转载 作者:行者123 更新时间:2023-11-28 13:14:04 25 4
gpt4 key购买 nike

我正在使用的第三方工具构建了一个像这样的 anchor 标记..

"<a href="http://DevNode/Lists/Publications.aspx#/publication/123">http://DevNode/Lists/Publications.aspx#/publication/123</a>"

我需要隔离 href,以便可以 trim 它。目前我的模式

reg = /^(<a\shref=")? http:\/\/DevNode\/Lists\/Publications.aspx#\/publication\/(\d+)/i {lastIndex: 0} 

如果href有这样的前导空格,将无法匹配

"<a href=" http://DevNode/Lists/Publications.aspx#/publication/123"> http://DevNode/Lists/Publications.aspx#/publication/123</a>"

请帮忙

最佳答案

如果您在浏览器上执行此操作,最简单的方法是让浏览器自行计算:

var div = document.createElement("div");
div.innerHTML = yourString;
var href = div.querySelector("a").href;

如果它是相对 URL,这还有一个优点:可以解析它。如果您不希望这样,请改用 getAttribute:

var href = div.querySelector("a").getAttribute("href");

请注意,如果您使用getAttribute,如果该属性有前导空格,则前导空格出现在结果中;如果您想摆脱它,String#trim 可能会很有用。

关于javascript - 如何在Javascript中获取字符串的href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092721/

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