我有一些奇怪的问题“改进”书签。 我把这个例子从here - 它需要表达式匹配的页面上的正则表达式,并强调文本 - 我已经重新格式化它使用JSMin记事本++轻松阅读:两个正则表达式JavaScript书签之间的差异
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的行为似乎没有差异。在第二个中使用新的正则表达式(...)并没有帮助 - 我使用斜杠符号来保存其余部分的斜杠,使其不易读。
会有人愿意指出我对我的错误吗?
不确定您的正则表达式是否有效。尝试'/ \ b(who | who | ... |恶心)\ b/i'(在外面休息,但 - 更重要的是 - 分支周围的人) – Flambino 2012-02-14 16:50:10