This must have an answer somewhere already, but I don't even know what to search for.
In JavaScript, I can reference a parenthesized submatch in a replacement string like so:
"abcdefghijklmnopqrstuvwxyz".replace(/(.)/g, "$1-");
// Result: "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-"
Now, I want to put a 1
instead of a -
in between each letter:
"abcdefghijklmnopqrstuvwxyz".replace(/(.)/g, "$11");
// Result: "a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1z1"
At least Chromium seems to detect that there is no submatch group 11, so it interprets the replacement string as "submatch group 1 followed by a 1".
Let's assume there are 11 groups though:
'abcdefghijklmnopqrstuvwxyz'.replace(/^(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)$/, '$11');
// Result: "k"
What I would like to know:
- Will example 2 work cross browser? Is it defined somewhere that it should behave like this?
- Is there a way to explicitly delimit the submatch group reference? Something like in bash where
$a
and${a}
refer to the same variable, but the latter makes it possible to delimit it from the following text. Something that would enable me to make example 3 output"a1"
rather than "k".