0

So if I were to have a string like "111" how can I turn "111" into [1, 1, 1]. Cause if I were to use .split(', ') on the string itself then I would get ['111'].

2 Answers2

1

We can doing a regex split on the lookahead (?=.):

parts = "111".split(/(?=.)/);
console.log(parts);

The lookahead (?=.) will fire true at every position in between characters, but would fail for the position after the very last character in the string. Note that lookarounds assert, but do not consume. They get around the problem of using just (.), which would match each letter, but would also consume it in the process.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

let para = "111";  
let arr = para.split('').map(Number);
console.log(arr);   // [1, 1, 1]
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22