Javascript/RegEx 在文件名周围添加 <b> 标签

标签 javascript regex

我想要做的是找到页面上的所有文件名/文件路径,并使用 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/

相关文章:

javascript - JS : fullpage. 不同部分之间的 js moveTo()

javascript - Google Apps 脚本可以逐行读取 txt 吗?

javascript - 替换节点名称

mysql - 希望通过 MYSQL 提取字符串中括号之间的数据

javascript - 如何使用正则表达式匹配精确的字符串

python - 按条件从字符串中提取数字

javascript - 正则表达式匹配特定短语完成或不带感叹号?

javascript - 使用 bootstrap-markdown 上传图像

正则表达式在 MongoDB 中说不是这个字符

javascript - 正则表达式匹配URL参数