我遇到了一些“改善”书签的怪异问题。
我从here取得了这个示例-它需要一个正则表达式,并在与该表达式匹配的页面上突出显示文本-我已经对其格式进行了重新格式化,以便使用JSMin for Notepad ++轻松阅读:
javascript : (function () {
var count = 0,
text,
regexp;
text = prompt("Search regexp:", "");
if (text == null || text.length == 0)
return;
try {
regexp = new RegExp("(" + text + ")", "i");
} catch (er) {
alert("Unable to create regular expression using text '" + text + "'.\n\n" + er);
return;
}
function searchWithinNode(node, re) {
var pos,
skip,
spannode,
middlebit,
endbit,
middleclone;
skip = 0;
if (node.nodeType == 3) {
pos = node.data.search(re);
if (pos >= 0) {
spannode = document.createElement("SPAN");
spannode.style.backgroundColor = "yellow";
middlebit = node.splitText(pos);
endbit = middlebit.splitText(RegExp.$1.length);
middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
++count;
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && node.tagName.toUpperCase() != "SCRIPT" && node.tagName.toUpperCase != "STYLE") {
for (var child = 0; child < node.childNodes.length; ++child) {
child = child + searchWithinNode(node.childNodes[child], re);
}
}
return skip;
}
window.status = "Searching for " + regexp + "...";
searchWithinNode(document.body, regexp);
window.status = "Found " + count + " match" + (count == 1 ? "" : "es") + " for " + regexp + ".";})();
这是我对单击的高亮显示的前10行的定制改进:
javascript : (function () {
var count = 0,
regexp;
try {
regexp = /\bwho\b|\bwhom\b|\blay\b|\blie\b|\bmoot\b|\bcontinual\b|\bcontinuous\b|\benvy\b|\bjealousy\b|\benvious\b|\bjealous\b|\bnor\b|\bmay\b|\bmight\b|\bwhether\b|\bfewer\b|\bless\b|\bdisinterested\b|\buninterested\b|\bdifferent than\b|\bimpactful\b|\baffect\b|\beffect\b|\birony\b|\bironic\b|\bnauseous\b/i;
} catch (er) {
alert("Unable to create regular expression\n\n" + er);
return;
}
...
第一种有效,第二种无效。将表达式从第二个复制到提示中时,第一个甚至可以工作。
当第二个运行时,浏览器会消耗CPU一段时间,然后突出显示下蹲。第一个是即时的。 IE9 / Chrome17 / FF10之间的行为似乎没有什么不同。在第二个中使用新的Regex(...)并没有帮助-我使用斜杠表示法来节省不得不将其余部分加倍的斜杠,从而降低了可读性。
有人愿意指出我的错误吗?
最佳答案
您在表达式中省略了“(”和“)”。
这有效:regexp = /(\ bwho \ b | \ bwhom \ b | \ blay \ b | \ blie \ b | \ bmoot \ b | \ bcontinual \ b | \ bcontinuous \ b | \ benvy \ b | \ bjealousy \ b | \以前的\ b | \ bjealous \ b | \ bnor \ b | \ bmay \ b | \ bmight \ b | \ b \\ b \\ bfewer \ b | \ bless \ b | \ b不感兴趣\ b | \ buninterested \ b | \不同于\ b | \ bimpactful \ b | \ baffect \ b | \ beffect \ b | \ birony \ b | \ bironic \ b | \ bunseous \ b)/ i;
如果您问我为什么需要括号,我不知道。与更下游的代码相关的是我的有根据的猜测。我所做的只是比较原始代码和您的代码之间的区别;考虑到表达式在输入框中输入后起作用的事实。
关于javascript - 两个正则表达式JavaScript小书签之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280195/