I am trying to split a string by regex and getting an unexpected result:
var str = 'name == abcd';
var pattern = /([^!=>< ]+)\s*([!=><]+)\s*(.)+/i;
pattern.exec(str);
the result of the example is : [ "name == abcd", "name", "==", **"d"** ]
why "d" and not "abcd"?
The capturing group
(.)only captures one character. The construct(.)+means “one or more capturing groups, each containing one character”. It returns only “d” because that is the last iteration of the capturing group encountered.If you move the repetition inside the capturing group,
(.+), you will then have asked for “a capturing group containing one or more characters”. This is probably what you want.