我正在尝试用javascript创建一个自动链接功能,该功能在用户键入(ContentEditablediv)时自动将url转换为链接。
我使用这个正则表达式:
var text = 'Some text containing URLs';
var exp = /(b(http)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
var newtext = text.replace(exp,"<a href='$1'>$1</a>");
上面的代码运行良好,但由于每次用户键入时都会调用代码,因此会发生递归:
<a href='<a href='<a href=' etc.
如何避免这种情况发生,同时让脚本在用户键入时更新文本?
所以问题是(谢谢@putvande):我该如何检查URL是否已经包含:
<a href='...
(我对regex不是很在行)
您只能匹配那些没有前缀为>
或'
的URL模式。虽然这可能不是100%万无一失的,但它应该足以让你开始。
function urlify(text) {
var exp = /^>(b(http)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
称之为:
urlify('Some text http://example.com containing URLs');
返回"Some text <a href='http://example.com'>http://example.com</a> containing URLs"
urlify("Some text <a href='http://example.com'>http://example.com</a> containing URLs");
返回"Some text <a href='http://example.com'>http://example.com</a> containing URLs"