text: Q:
  
  split() works differently with more than one whitespace
  
  I am trying to replace the first letter of every word in a string to uppercase and got it working by splitting the string then mapping through each word as follows:  
  var S = 'hello world';
  var x = S.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
  
  console.log(x);
  
  BUT:
  If the string contains more than one white-space as follows, I get an error Cannot read property 'toUpperCase' of undefined.
  var S = 'hello   world';
  var x = S.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
  
  console.log(x);
  
  I tried adding a + to .split(' ') and .join(' ') as recommended in past stackoverflow threads as follows but doing that only capitalises the first letter of the first word instead:
  var S = 'hello    world';
  var x = S.toLowerCase().split(' +').map(word => word[0].toUpperCase() + word.substr(1)).join(' +');
  
  console.log(x); // returns 'Hello    world'
  
  What would be the right way to go about this?
  
  A:
  
  You can use String.replace() with a RegExp to replace just the 1st character of each word with an upper case version:
  
  var S = 'hello   world';
  var x = S.toLowerCase().replace(/\b\w/g, (m) => m.toUpperCase());
  
  console.log(x);
  
  If you still want to use String.split(), use RegExp, and split the array by \s+ (a sequence of spaces - space, tab, etc...):
  
  var S = 'hello   world';
  var x = S.toLowerCase().split(/\s+/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
  
  console.log(x);
  
  