views:

73

answers:

2

Hello please help me

 <html>
  <body>
       http://domainname.com/abc/xyz.zip
       http://domainname2.com/abc/xyz.zip 

 </body>
 </html>

I want replace with link and out put like

 <html>
  <body>
      <a href="http://domainname.com/abc/xyz.zip"&gt;http://domainname.com/abc/xyz.zip&lt;/a&gt;
      <a href="http://domainname2.com/abc/xyz.zip"&gt;http://domainname2.com/abc/xyz.zip&lt;/a&gt;

 </body>
 </html>

Great Thank

+1  A: 

You should not use regular expressions to parse HTML.

VeeArr
He's not, he wants a regular expression to replace text with HTML.
Andy E
Except that this requires you to be aware of the link's context. What if the link is already inside of an `<a>` tag?
VeeArr
A: 

Try this function:

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

This is pure DOM manipulation. This linkify function expects the argument to be a HTMLElement. You just need to adjust the regular expression to grab the URLs.

Gumbo