Javascript将网络位置的所有实例替换为超链接

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

本文关键字:实例 替换 超链接 网络 位置 Javascript      更新时间:2023-09-26

我试图写一些javascript执行将搜索html列出的所有网络位置(例如。''server'file)并将其转换为超链接(例如。<a href="''server'file">''server'file</a>)

我对如何做到这一点有点困惑,我已经做了一些搜索,但还没有真正找到任何合适的。我想我应该使用正则表达式。

有人能帮忙吗?我必须承认,对于正则表达式

,我还是个新手。

如何使用jQuery选择文本节点?是个好的开始。您的方法基本上是获取文档中的所有文本节点,搜索文件模式,并用超链接替换。

示例(您可能需要调整以从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);