我想要做的是找到页面上的所有文件名/文件路径,并使用 javascript 将它们设置为粗体。
一些示例文件名/路径是:
- \服务器\文件夹
- \服务器\文件夹\
- \服务器\文件夹\文件名.txt
- c:\
- c:\文件夹
- c:\文件夹\
- c:\文件夹\文件名.txt
以下示例将使用正则表达式模式“test.t..”查找字符串并将其变为粗体(即,将查找 test.txt 并将其变为粗体)。我需要将该正则表达式更改为可以查找文件名/文件路径的正则表达式(仅使用一个简单的示例,我自己对文件名/文件路径正则表达式没有任何运气)。
findAndReplace(document);
function findAndReplace(root) {
var children = root.childNodes;
var pattern = new RegExp('test.t..', 'ig');
var node;
for(var i = 0, l = children.length; i < l; i++) {
node = children[i];
if(node.nodeType === 3) { // we have a text node
if (node.nodeValue.match(pattern)){
var newValue = "<b>" + node.nodeValue.match(pattern) + "</b>";
node.parentElement.outerHTML = node.parentElement.outerHTML.replace(pattern, newValue);
}
} else if(node.nodeType === 1) { // Element node
findAndReplace(node);
}
}
}
最佳答案
这是一个可以尝试的模式:
var pattern = /([a-z]:)?(\\\w+)+(\\|\.\w{3,4})?/;
说明:
([a-z]:)? - optionally starts with a drive letter and colon
\\ - backslash
\w+ - folder name
(\\\w+)+ - several subfolders possible
(\\|\.\w{3,4})? - optionally ends with a backslash or file extension
note that the file name would be caught by (\\\w+)+
关于Javascript/RegEx 在文件名周围添加 <b> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15525318/