-1

how to split a string number to be arrays example :

var str = "124590"
var str2 = "12459010"

// output:
["12", "45", "90"]
["12", "45", "90", "10"];

and how to make those array strings to be number also in the array, and if we use regex, could it work? thx

Zr Classic
  • 303
  • 4
  • 14
  • If you have written code for this that you can't get to work, then you have come to the right place. Just [edit] the question and add the relevant parts of your code into it, because without that we cannot help. Also please see **[ask]**. – Peter B Oct 29 '18 at 12:07

2 Answers2

3

You can use something like this to split it every 2 characters:

var str = "124590";
var str2 = "12459010";

let regex = /\d{2}/g;
let array = str.match(regex);
let array2 = str2.match(regex);

console.log(array);
console.log(array2);

\d matches any digit, {2} makes sure it matches twice. The g part makes sure it matches every occurance and doesn't stop at the first match.

Mark
  • 5,089
  • 2
  • 20
  • 31
0

A string is basically an array of characters, so you can loop through it:

var str1 = "124590"

function splitMe(str) {
  var arr = []
  for (let i = 0; i < str.length; i++) {
    arr.push(str[i]+str[i+1])
    i++
  }
  return arr
}

console.log(splitMe(str1))
console.log(splitMe("1241389572489651"))
messerbill
  • 5,499
  • 1
  • 27
  • 38