嘿伙计们我创建了以下正则表达式函数来添加链接到传递的字符串,函数看起来像这样:
function addLinks(str) {
return str.replace( RegExp('https://[^/\s]+' , 'g') , (match , p1) => '<a href="' + match + '">' + match + '</\a>');
}
现在当我传递上述函数时,如下所示:
Go through codepens and make experiments folder -- https://codepen.io/pens/
我得到以下输出:
<li>Go through codepens and make experiments folder -- <a href="https://codepen.io">https://codepen.io</a>/pens/</li>
链接/pens/
的最后一部分未包含在链接中,为什么会发生这种情况,即使我添加了[^/\s]+
?
答案 0 :(得分:1)
你可以尝试匹配,直到碰到一个空格字符:
function addLinks(str) {
return str.replace( RegExp('https://[^\s]+' , 'g') , (match , p1) => '<a href="' + match + '">' + match + '</\a>');
}
这可能有效,因为有效网址中不能包含空格。当然,这个正则表达式会错过URL上的标记。