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']
.
Asked
Active
Viewed 78 times
0
-
6`"111".split("")` ?? – Krishna Prashatt Aug 19 '19 at 05:03
-
1Notice, that the argument of `split` is meant to be the character which to split by, not a separator in the array to be created. – Teemu Aug 19 '19 at 05:04
-
2There's also `[...str]` and you might want to `.map(e => +e)` to get ints. – ggorlen Aug 19 '19 at 05:09
-
@ggorlen thx will give a try – Aug 19 '19 at 05:28
2 Answers
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
-
6Wondering about the reason to use such a (complicated) lookahead instead of simply `.split('')` – zerkms Aug 19 '19 at 05:06
-
1@zerkms No reason...I didn't know about that trick, or else I would have suggested it as well. – Tim Biegeleisen Aug 19 '19 at 05:07
1
let para = "111";
let arr = para.split('').map(Number);
console.log(arr); // [1, 1, 1]

Rahul Kumar
- 3,009
- 2
- 16
- 22
-
3If you used `Number` you could have shortened it to a nicely looking `.map(Number)` – zerkms Aug 19 '19 at 05:11
-