I am trying to split the numbers including ‘-‘ values. but getting different values.
const arr = '2345-10'.split('');;
console.log(arr);
result : ['2', '3', '4', '5', '-', '1', '0']
But expecting a result like this:
['2', '3', '4', '5', '-1', '0']
2
Answers
.split('');
will turn each character in the string into an item in the resulting array (for characters that aren’t surrogate pairs, at least). If you want a-
, when it appears, to stick to the number that follows, you’ll need a different approach, such as a regular expression that matches a digit with an optional leading-
.But note that due to the format of the input string, this will only work if you always want single digits.
23
will always be interpreted as'2', '3'
and not'23'
.If you don’t want to use regex, just split it and detect if the previous element of
n
is'-'
, then return-n
and filter it so that the final result contains no'-'
.