开发者

Javascript to replace all instances of a network location with a hyperlink

开发者 https://www.devze.com 2023-04-05 19:57 出处:网络
I\'m trying to write s开发者_Python百科ome javascript which executed will search the html for all network locations listed (eg. \\\\server\\file) and convert them to a hyperlink (eg. <a href=\"\\\\

I'm trying to write s开发者_Python百科ome 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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号