JavaScript regex backlinks return an array of matches from one capture group (multiple groups)

I am pretty sure, having spent the night trying to find the answer that this is not possible, and I developed the work, but if someone knows the best method, I would love to hear that ...

I have done many iterations over the code, and the following is just a line of thought. At some point I use the global flag, I suppose, for match () to work, and I can’t remember whether it was necessary now or not.

var str = "@abc@def@ghi&jkl";
var regex = /^(?:@([a-z]+))?(?:&([a-z]+))?$/;

The idea here in this simplified code is an optional group 1, of which there is an indefinite amount, will correspond to @abc, @def and @ghi. It will only capture alpha characters, of which there will be one or more. Group 2 is the same except matches and characters. It should also be tied to the beginning and end of the line.

I want to be able to refer back to all matches of both groups, that is:

result = str.match(regex);
alert(result[1]); //abc,def,ghi
alert(result[1][0]); //abc
alert(result[1][1]); //def
alert(result[1][2]); //ghi
alert(result[2]); //jkl

My assistant says that this works fine for him in .net, unfortunately, I just can’t get it to work - only the last one matched to any group returns to the backlink, as can be seen from the following:

(in addition, adding a group does not necessarily create a mess, like setting a global flag)

var str = "@abc@def@ghi&jkl";
var regex = /(?:@([a-z]+))(?:&([a-z]+))/;

var result = str.match(regex);

alert(result[1]); //ghi
alert(result[1][0]); //g
alert(result[2]); //jkl

The following is the solution I came to, capturing the entire part in question, and creating an array:

var str = "@abc@def@ghi&jkl";
var regex = /^([@a-z]+)?(?:&([a-z]+))?$/;

var result = regex.exec(str);

alert(result[1]); //@abc@def@ghi
alert(result[2]); //jkl

var result1 = result[1].toString();
result[1] = result1.split('@')

alert(result[1][1]); //abc
alert(result[1][2]); //def
alert(result[1][3]); //ghi
alert(result[2]); //jkl
+5
1

, .match() JavaScript. . "" ; ( .

( [0]) . , ( null) .

, , . .

edit — oh, , result[1][0] "g", , , , .

+4

All Articles