我要检测Javascript文本中的url,您能告诉我此功能出了什么问题吗?
function findUrl() {
var text = document.getElementById("content");
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
findUrl();
答案 0 :(得分:2)
text
不是字符串,而是DOMElement
。也许你想要
var text = document.getElementById("content").value; // if #content is an <input>
// or
var text = document.getElementById("content").textContent;
答案 1 :(得分:0)
我可能会简化为:
function findUrl() {
var text = document.getElementById("content").textContent;
var urlRegex = /(\b(https?|ftp|file):\/\/\S+)/gi;
return text.replace(urlRegex, function(url) {
return `<a href="${url}">${url}</a>`;
});
}