请帮帮我
<html>
<body>
http://domainname.com/abc/xyz.zip
http://domainname2.com/abc/xyz.zip
</body>
</html>
我希望用链接和输出替换
<html>
<body>
<a href="http://domainname.com/abc/xyz.zip">http://domainname.com/abc/xyz.zip</a>
<a href="http://domainname2.com/abc/xyz.zip">http://domainname2.com/abc/xyz.zip</a>
</body>
</html>
非常感谢
答案 0 :(得分:1)
您should not use regular expressions要解析HTML。
答案 1 :(得分:0)
尝试此功能:
function linkify(element) {
var children = element.childNodes,
stub = document.createDocumentFragment();
for (var i=0; i<children.length; ++i) {
if (children[i].nodeType === Node.TEXT_NODE) {
var parts = children[i].nodeValue.split(/(http:\/\/\S+)/); // adjust regex
if (parts.length > 1) {
for (var j=0; j<parts.length; ++j) {
if (j % 2 === 1) {
var link = document.createElement("a");
link.setAttribute("href", parts[j]);
link.appendChild(document.createTextNode(parts[j]));
stub.appendChild(link);
} else {
stub.appendChild(document.createTextNode(parts[j]));
}
}
continue;
}
}
stub.appendChild(children[i]);
}
document.write(stub.childNodes.length);
element.parentNode.replaceChild(stub, element);
}
linkify(document.body);
这是纯粹的DOM操作。此linkify
函数要求参数为 HTMLElement 。您只需调整正则表达式即可获取URL。