JavaScript正则表达式,匹配和替换链接

时间:2010-06-15 15:30:16

标签: javascript regex

请帮帮我

 <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>

非常感谢

2 个答案:

答案 0 :(得分:1)

答案 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。

相关问题