Search code examples
javascriptsplitconcatenation

Split(" ") 3 spaces returns 2 empty strings instead of 1?


I am having trouble understanding the split method in which there is 3 spaces between 2 characters in a string. For example is if there is a string that looks like this "a b" and I try to use JS's split function, it will return ['a','','','b'] instead of ['a','','b']. Why is this happening and how do I achieve ['a','','b'] instead?

const threeSpaces = 'a   b'
console.log(threeSpaces.split(' '))


Solution

  • let threeSpaces = 'a      b';
    threeSpaces = threeSpaces.replace(/\s\s+/g, '  ');
    const result = threeSpaces.split(' ');
    console.log(result);