You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何从HTML代码中提取href属性内的激活链接

HTML字符串href属性提取实现方案

以下两种实现方案都兼容动态变化的token id,可直接使用:

方案1:DOMParser解析(优先推荐)

适合浏览器环境或者支持DOM API的运行环境,解析逻辑完全不依赖href内容格式,容错性最高,就算后续token规则调整也不会失效:

const body = `<html><head></head><body><p>This is SignUp Email with confirmation link</p><p><a href = "http://www.company.com/ls/click?upn=tokenid-11111-22222-333333-444444-555555-xxxxxx"></a></p></body></html>`

const parser = new DOMParser()
const htmlDoc = parser.parseFromString(body, 'text/html')
const activation_link = htmlDoc.querySelector('a').href

console.log(activation_link)

方案2:正则匹配

适合Node.js等无DOM API的运行环境,正则会自动匹配带upn参数的完整链接,不受动态token影响:

const body = `<html><head></head><body><p>This is SignUp Email with confirmation link</p><p><a href = "http://www.company.com/ls/click?upn=tokenid-11111-22222-333333-444444-555555-xxxxxx"></a></p></body></html>`

const activation_link = body.match(/href\s*=\s*["'](http:\/\/www\.company\.com\/ls\/click\?upn=[^"']+)["']/)[1]

console.log(activation_link)

两种方案运行后都会在控制台输出你需要的完整激活链接。


内容的提问来源于stack exchange,提问作者Tom Nemeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:06:06