我正在尝试在javascript中创建自动链接功能,在用户输入(ContentEditable div)时自动将网址转换为链接。
我使用这个正则表达式:
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='...
(我对正则表达式并不是很方便)
答案 0 :(得分:0)
您只能匹配那些没有>
或'
前缀的网址格式。虽然这可能不是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"