最佳开源链接解析器

时间:2019-05-27 20:11:47

标签: javascript regex hyperlink xml-parsing html-parsing

我正在寻找一段文本并标记任何链接,例如任何消息传递或电子邮件应用程序将如何进行链接。我已经推出了自己的正则表达式解决方案,但遇到了一些极端情况。这似乎是一种常见的情况,似乎必须有一个可以处理所有这些问题的开源库,但是我在进行任何Google或StackOverflow或Github搜索方面都没有成功。有没有人对此熟悉任何库?举几个例子:

Hello, www.link.com, is a link and http://hello.com?new=123,145#141 is also a link.

Hello, www.link.com, is a link and http://hello.com?new=123,145#141 is also a link.

请注意,StackOverflow本身缺少链接(尽管该链接非常明显,出于某种原因,我认为这是故意的),更好的标记是Gmail:

enter image description here

是否有经过战斗验证的开源库可以满足我的需求?换句话说,我正在做这样的事情:

var text = "Hello, www.link.com, is a link and http://hello.com?new=123,145#141 is also a link."
markupText(text)
"Hello, <a href="www.link.com">www.link.com</a>, is a link and <a href="http://hello.com?new=123,145#141">http://hello.com?new=123,145#141</a> is also a link."

1 个答案:

答案 0 :(得分:0)

该任务很可能无法完成,因为您可能希望执行该任务,但是我们可以尝试一个可能部分解决该问题的解决方案,但是随着我们输入内容的改变,它可能会失败。一个示例表达式为:

(.+?)((www|http).+?),?[\s]

const regex = /(.+?)((www|http).+?),?[\s]/gm;
const str = `Hello, www.link.com, is a link and http://hello.com?new=123,145#141 is also a link.`;
const subst = `$1<a href="$2">$2</a> `;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Demo

参考

相关问题