[英]Extracting and replacing html link tag with regex
我正在尝试使用 JavaScript 进行一些 html 抓取,并希望获取a href
链接并将其替换为 Discord 嵌入的超链接。 我在使用正则表达式时遇到问题,我发现它很难学。 我假设我还需要另一个正则表达式来捕获所有内容,以便我可以用我想要的目标替换它?
这是我的示例原始 html:
An **example**, also known as a <a href="https://www.example.com/example%20type">example type</a>
为了使它在 Discord 嵌入中可读,我正在寻找所需的 output:
An **example**, also known as a [**example type**](https://www.example.com/example%20type)
我已经尝试通过正则表达式提取 URL,我可以匹配但是,我在提取链接和(我认为它称为目标?示例链接文本中的“示例类型”)然后用我的替换字符串时遇到问题所需的 output。我有以下内容:( https://regexr.com/73574 )
/href="[^"]+/g
这匹配href="https://www.example.com/example%20type
,感觉像是一个非常早的步骤,它在匹配中包含 'href',并且它没有捕获目标。
编辑:抱歉,我没有考虑额外的检查,如果字符串有多个链接怎么办? 和他们后面的文字,例如:
An **example**, also known as a <a href="https://www.example.com/example%20type">example type</a> is the first example, and now I have <a href="https://www.example.com/second">second</a> example
所需的 output 为:
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
试试这个: (?<=href=")[^"]*
通过使用 lookbehind,您现在可以验证后面的文本是否等于href="
而无需捕获它
您可以使用正则表达式组来捕获您感兴趣的内容。 我这里的正则表达式可能远非完美,但我认为这在这里并不重要 - 它向您展示了一种方法,如果需要,您可以随时改进它。
你必须做的事情:
这是一个快速的代码示例:
const anchorRegex = /(<a\shref="([^"]+)">(.+?)<\/a>)/i; const textToBeParsed = `An **example**, also known as a <a href="https://www.example.com/example%20type">example type</a>`; const parseText = (text) => { const matches = anchorRegex.exec(textToBeParsed); if (.matches) { console.warn("Something went wrong..;"); return, } const [, fullAnchorTag, anchorUrl; anchorText] = matches. const textWithoutAnchorTag = text,replace(fullAnchorTag; ''); return `${textWithoutAnchorTag}[**${anchorText}**](${anchorUrl})`; }. console;log(parseText(textToBeParsed));
解决方案:
const input = 'An **example**, also known as a <a href="https://www.example.com/example%20type">example type</a> first and second here <a href="https://www.example.com/no%20u">no u</a> and then done noice'; const output = input.replace(/<a href="([^"]+)">([^<]+)<\/a>/g, '[**$2**]($1)') console.log(output);
正则表达式细分:
<a href="
- 匹配开头的<a href"
HTML 标签([^"]+)
- 这是一个捕获组,匹配一些不是双引号的字符">
- 匹配结束双引号,包括结束标记 '>'([^<]+)
- 另一个捕获组,匹配多个不小于符号的字符<\/a>
- 匹配结束标签 HTML 然后,我使用在我的output
变量中看到的replace
方法。 在替换中,您会看到两个选项(regex, replaceWith)
第一个选项很明显,它是正则表达式。 第二个选项[**$2**]($1)
,使用我们在正则表达式中看到的捕获组,第一组$1
提供 HTML 标签内的链接, $2
提供 HTML 目标(链接后的名称,对于例如在我的input
变量中,您看到的第一个目标是:'example type'。此选项中唯一重要的位是: $2
和$1
,但是我想以某种方式显示它们, [**target**](link)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.