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?
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?
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)
);
function myFunction() {
var text = document.getElementById("input").value;
console.clear()
var re = /(.)(.{2})/g;
var m;
var arr = [];
do {
m = re.exec(text);
if (m) {
arr.push(m[1], m[2]);
}
} while (m);
console.log(arr)
}
<form action="javascript:myFunction()">
<input id="input" type="text" value="112213"><br><br>
<input type="submit" value="Submit">
</form>