Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to array with different length using regex

String to array with length 2 can be done like below.

let str1 = '112213';
let str1Array = str1.match(/.{2}/g);
console.log(str1Array);

And the result is

[ '11', '22', '13' ]

Is it possible to get [ '1', '12', '2' , '13'] similarly?

like image 276
shijin Avatar asked May 10 '26 02:05

shijin


1 Answers

You can use split() instead of match() providing both lengths in one regex:

(.)(..)?

Optional quantifier is essential when string length is not even.

JS Code:

console.log(
  '112213'.split(/(.)(..)?/).filter(Boolean)
);
like image 193
revo Avatar answered May 11 '26 16:05

revo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!