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

如何用正则提取替换HTML的a标签为Discord嵌入支持的链接格式?

解决方案

你需要用一个能同时捕获URL和链接文本的正则表达式,结合JavaScript的replace方法完成转换。

正则表达式说明

使用这个全局匹配的正则:

/<a href=&quot;([^&quot;]+)&quot;>([^<]+)<\/a>/g

各部分作用:

JavaScript代码示例

直接用replace方法将匹配内容替换为Discord支持的超链接格式:

// 原始HTML文本
const originalHtml = 'An **example**, also known as a <a href=&quot;https://www.example.com/example%20type&quot;>example type</a> is the first example, and now I have <a href=&quot;https://www.example.com/second&quot;>second</a> example';

// 正则替换
const discordEmbedText = originalHtml.replace(
  /<a href=&quot;([^&quot;]+)&quot;>([^<]+)<\/a>/g,
  '[**$2**]($1)' // $1对应捕获到的URL,$2对应捕获到的链接文本,**用于给文本加粗
);

console.log(discordEmbedText);

输出结果

运行后会得到你期望的格式:

An **example**, also known as a [**example type**](https://www.example.com/example%20type) is the first example, and now I have [**second**](https://www.example.com/second) example

注意事项

如果你的HTML里存在嵌套标签(比如内还有),这个正则可能无法正确提取文本,这种情况建议用DOM解析库处理,但对于你给出的纯文本链接场景,这个正则完全够用。

内容的提问来源于stack exchange,提问作者Venom John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:01:09