问问题
480 次
3 回答
0
快速回答:http: //jsfiddle.net/dCE9k/1/
我稍微更改了您的代码,请参阅小提琴以获取工作示例。
正则表达式应如下所示:
/([a-zA-Z]:)?([\/\\])([a-zA-Z0-9\.]\2?)*/ig;
它关心驱动器号,捕获目录分隔符并在整个文件路径中重用它。允许大写、小写、数字和点作为有效的文件名。
我使用了这个演示 HTML 代码
<p>\server\folder</p>
<p>\server\folder\</p>
<p>\server\folder\filename.txt</p>
<p>c:\</p>
<p>c:\folder</p>
<p>c:\folder\</p>
<p>c:\folder\filename.txt</p>
我稍微调整了你的 JS 代码:
findAndReplace(document);
function findAndReplace(root) {
var children = root.childNodes;
var pattern = /([a-zA-Z]:)?([\/\\])([a-zA-Z0-9\.]\2?)*/ig; // applied new regex
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 (pattern.test(node.nodeValue)){ // This line changed (maybe not required)
var newValue = "<b>" + node.nodeValue.match(pattern) + "</b>";
node.parentElement.innerHTML = newValue; // This line changed
}
} else if(node.nodeType === 1) { // Element node
findAndReplace(node);
}
}
}
于 2013-03-20T14:12:15.610 回答
0
这是一个尝试的模式:
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+)+
于 2013-03-20T13:57:34.930 回答
0
我尝试了您的代码,但它不起作用......即使我更正了正则表达式......
于是就有了解决办法:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script>
function findAndReplace(root) {
var children = root.childNodes;
var pattern = /([a-zA-Z]:[\\\/]|[\\\/])(\w+[\\\/])*\w+\.\w{3}/g;
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 mySpan = document.createElement("span");
mySpan.innerHTML = "<b>" + node.nodeValue.match(pattern) + "</b>";
node.parentNode.replaceChild(mySpan, node);
}
} else if(node.nodeType === 1) { // Element node
findAndReplace(node);
}
}
}
</script>
</head>
<body onload="javascript:findAndReplace(document);">
<form name="myform" action="test" method="POST">
<div align="center"><br>
<input type="radio" name="group1" value="Milk" /> Milk.txt<br />
<input type="radio" name="group1" value="Butter" checked /> Butter.txt<br />
<input type="radio" name="group1" value="Cheese" /> Cheese.tes
<hr />
<input type="radio" name="group2" value="Water"/> /bonjour.tsh<br />
<input type="radio" name="group2" value="Beer" /> Beer.txt<br />
<input type="radio" name="group2" value="Wine" checked /> /Milk.txt<br />
</div>
/Milk.txt
</form>
c:/bonjour/Milk.txt<br />
c:\test.txt
</body>
</html>
于 2013-03-20T15:00:26.783 回答