skip to Main Content

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


  1. .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 -.

    const arr = '2345-10'.match(/-?d/g);;
    console.log(arr);

    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'.

    Login or Signup to reply.
  2. 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 '-'.

    const arr = '2345-10'.split('').map((n, index, array) => array.at(index - 1) === '-' ? '-' + n : n).filter(n => n !== '-');
    console.log(arr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search