3

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?

2
  • 2
    It may be possible, depending on the input strings you have and the meaning of array elements. In short: what do you want to match? Commented Feb 24, 2018 at 14:12
  • my mistake, just need to split with different length(here 1 and 2) Commented Feb 24, 2018 at 14:17

2 Answers 2

5

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)
);

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.