0

I'm trying to write some javascript which executed will search the html for all network locations listed (eg. \\server\file) and convert them to a hyperlink (eg. <a href="\\server\file">\\server\file</a>)

I'm a bit stumped on how to do this, I've done some searching but haven't really found anything suitable. I assume I should be using regular expressions.

Anybody able to help. I must admit I am very much a newb when it comes to regular expressions

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
BeepBoop
  • 184
  • 1
  • 2
  • 13
  • FYI, `\\server\file` won't work very well as an href in your HTML, at least not for most browsers I know. Creating a file URL like `file://///server/file` would work better. (yes, 5 forward slashes :/) – Jacob Sep 19 '11 at 23:39

1 Answers1

0

This answer to How do I select text nodes with jQuery? is a good start. Your approach would basically be to get all of the text nodes in your document, search for your file pattern, and replace with the hyperlinks.

Sample (you might want tweaking to strip trailing punctuation from match):

var pattern = /(^|\s)(\\\\.*?)(\s|$)/;

function linkifyRecursive(node) {

    if (node.nodeType == 3) {

        var text = node.nodeValue;
        var match = text.match(pattern);
        if (match) {

            var span = document.createElement('span');
            span.appendChild(document.createTextNode(
                text.substr(0, match.index + match[1].length)));

            var hyperlink = document.createElement('a');
            hyperlink.setAttribute('href', 'file:///' + match[2].replace(/\\/g, '/'));
            hyperlink.appendChild(document.createTextNode(match[2]));
            span.appendChild(hyperlink);

            span.appendChild(document.createTextNode(text.substr(match.index + match[0].length)));

            node.parentNode.replaceChild(span, node);
        }
    } else if (node.localName != 'script') {
        for (var i = 0, len = node.childNodes.length; i < len; ++i) {
            linkifyRecursive(node.childNodes[i]);
        }
    }
}

linkifyRecursive(document.body);    
Community
  • 1
  • 1
Jacob
  • 77,566
  • 24
  • 149
  • 228