Capitalise the first letter of each word using javascript

As an Example you’ve a full name john doe that you want it to be converted to John Doe when each first letter of the full name has to be in uppercase, to achieve that you’ll create a function that analyse a string entry and use regular expression to convert first letter to the uppercase form:

const capitalize = str => {
  const lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
};

And this is the output of using the function capitalize("john doe"):

John Doe