lyrically wicked lyrically wicked - 1 month ago 10
Javascript Question

How to highlight any amount of (possibly duplicated) As, followed by non-greedy matcher, then by any amount of Bs etc. (without unreasonable limits)?

The example below is a demo of the type of highlighting that I want (for

"a"
,
"b"
,
"c"
and
"d"
):



var reg = new RegExp("(.*?)([a]{1,})(.*?)([b]{1,})(.*?)([c]{1,})(.*?)([d]{1,})(.*?)", "gi");
var txt = "OK, abacd, abcdt, yaaaxxbyycccczzddddg0011".replace(reg,
'$1<mark>$2</mark>$3<mark>$4</mark>$5<mark>$6</mark>$7<mark>$8</mark>$9');
document.getElementById("test").innerHTML = txt;

<body>
<div id="test"></div>
</body>





The problem here is, obviously, a limit of
n=9
in
$n
. But what if I want to do this for more than four chars (that is, without unreasonable limits)? How to solve this?

Answer

An attempt using function as a parameter in replace()

This is more like dynamic pattern mentioned by @WiktorStribi┼╝ew

var reg = new RegExp(["a", "b", "c", "d"].map(a => "([" + a + "]{1,})(.*?)").reduce((a, i) => a + i, "(.*?)"), "gi");
var txt1 = "OK, abacd, abcdt, yaaaxxbyycccczzddddg0011"
  .replace(reg, (m, ...p) => {
    p.pop();//pop string
    p.pop();//pop offset
    return p.reduce((a, i, ix) => a + (ix % 2 ? "<mark>" + i + '</mark>' : i), '')
  });

var txt = "OK, abacd, abcdt, yaaaxxbyycccczzddddg0011"
  .replace(reg, (m, ...p) => {
    p.pop();
    p.pop();
    return "<br><br>-match-" + m + p.reduce((a, i, ix) => a + "<br>-substring-" + (ix % 2 ? i : "-h-" + i), '')
  });
document.getElementById("test").innerHTML = txt1 + txt;
<body>
  <div id="test"></div>
</body>

Comments