我想突出显示在网页上显示的所有6个字母的回文。我找到了这个javascript函数JSFiddle并相信我已经相应地调整了它。
function highlight() {
var query = new RegExp("([ATCG])([ATCG])([ATCG])(\\3)(\\2)(\\1)", "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>$1</span>");
document.getElementById("searchtext").innerHTML = newe;
}
当我运行该功能(通过单击链接)时,没有任何文本突出显示。如果只是在那里放一个常规字符串就行了,所以我认为这是正则表达式给出问题,但在线测试并发现它有效。 RegEx Test
答案 0 :(得分:2)
更多 intuivite 细分,包括大小写匹配:
function highlightPal() {
var e = document.getElementById("searchtext");
e.innerHTML = e.innerHTML
.replace(/(<span>|<\/span>)/igm, "")
.replace(
new RegExp("([A-Za-z])([A-Za-z])([A-Za-z])(\\3)(\\2)(\\1)","gim"),
"<span>$&</span>"
);
}
function highlightPal() {
var e = document.getElementById("searchtext");
e.innerHTML = e.innerHTML
.replace(/(<span>|<\/span>)/igm, "")
.replace(
new RegExp("([A-Za-z])([A-Za-z])([A-Za-z])(\\3)(\\2)(\\1)","gim"),
"<span>$&</span>"
);
}
highlightPal();
&#13;
span{background:#FF9;color:#555;}body{font-family:Arial,Helvetica,sans-serif;padding:0 1em;}p{margin:.8em 0;}
&#13;
<div id="searchtext"><p>JavaScript is the programming language of the Web. The overwhelming CGTTGCAATTAAGGCCGG browsers—on desktops, game consoles, tablets, and smart phones—include JavaScript pallap interpreters, making its first-class functions hoooooooooh from Scheme, terms, to use this book and learn JavaScript.</p><p>The name oooooooooooooooo"JavaScript" is actually rerrer somewhat misleading. <span>Except</span> for a scripting-language tuttut roots to become a robust and efficient general-purpose language.</p> </div>
&#13;
答案 1 :(得分:0)
由于您的RegEx构造函数定义中的括号创建了另一个捕获组,因此无效。
var query = new RegExp("(\\b" + text + "\\b)", "gim");
我使用的正则表达式是([a-z])([a-z])([a-z])\3\2\1
,它应该是硬编码的。这是功能:
function highlightSearch() {
var text = document.getElementById("query").value;
var query = new RegExp("(?:\\b([a-z])([a-z])([a-z])\\3\\2\\1\\b)", "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>$&</span>");
document.getElementById("searchtext").innerHTML = newe;
}
答案 2 :(得分:-1)
以下是使用match
和replace
执行此操作的另一种方式:
function highlight() {
var regex = /([ATCG])([ATCG])([ATCG])(\3)(\2)(\1)/gim;
var e = document.getElementById("searchtext").innerHTML;
var enew = e.match(regex);
for (var i = 0; i < enew.length; i++) {
e = e.replace(enew[i], '<span>' + enew[i] + '</span>');
}
document.getElementById("searchtext").innerHTML = e;
}
highlight();
&#13;
#searchtext span:nth-child(n) {
color: red;
}
#searchtext span:nth-child(2n) {
color: blue;
}
&#13;
<div id="searchtext">ATTTTAACTGTGATTAGGRAAGCCGAYAYCGTTGCAATTAAGGCCGG</div>
&#13;