我正在尝试编写一些javascript,执行后将搜索html列出的所有网络位置(例如\\server\file
)并将其转换为超链接(例如<a href="\\server\file">\\server\file</a>
)
我有点难过如何做到这一点,我做了一些搜索,但没有找到任何合适的东西。我假设我应该使用正则表达式。
任何人都可以提供帮助。我必须承认,当谈到正则表达式时,我非常喜欢新手
答案 0 :(得分:0)
This answer到How do I select text nodes with jQuery?是一个好的开始。您的方法基本上是获取文档中的所有文本节点,搜索文件模式,并替换为超链接。
示例(您可能需要调整以从匹配中删除尾随标点符号):
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);