匹配零次或多次对于零匹配无法正常工作

Match zero or more times not working properly for zero matches

本文关键字:常工作 工作 零次 于零匹      更新时间:2023-09-26

我正试图从以下两种类型的URL中获取URL和链接文本:

<a href="http://www.example.com">Example</a>
<a href="http://www.example.com" rel="nofollow">Example</a>

一开始我有这个:

text = text.replace(/<a href="(.*)">(.*)<'/a>/gim, "[$2]($1)");

但是这包括第二示例的CCD_ 2中的rel="nofollow"。我把它改成:

text = text.replace(/<a href="(.*)"( rel=".*"{0,})>(.*)<'/a>/gim, "[$3]($1)");

现在,rel="nofollow"链接是完美的,但第一个示例根本不匹配。

{0,}应表示"匹配rel=".*" 0次或更多次"。

我做错了什么?

您的表达式说"查找一个报价零次或多次;)

使用:

text = text.replace(/<a href="([^"]*)"[^>]*>(.*?)<'/a>/gim, "[$3]($1)"); 
jQuery解决方案:
var text_html_string = '<a href="http://www.example.com">Example</a>';
$(text_html_string).attr('href'); // http://www.example.com
$(text_html_string).text(); // Example

编辑不带jQuery

var d = document.createElement('div');
d.innerHTML = '<a href="http://www.example.com">Example</a>';
d.getElementsByTagName('a')[0].href; // http://www.example.com