0

I was searching for a solution to capitalize first letter of each word in a string and i got solution from stack overflow.

function convert_case(str) {
  var lower = str.toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

This code works. But i didn't understood what this code means? Any one please describe it.

  • ...combined with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace of course. – T.J. Crowder Mar 18 '17 at 19:29
  • E.g.: It matches either the beginning of the string or a space (`(^| )`) followed by a word character (`\w`), globally (`g`) through the string. `replace` calls the callback with the result of each match, and replaces the match with what the callback returns. Both of the capture groups in the regex are unnecessary, though; a single non-capturing group would be more appropriate: `/(?:^| )\w/g` – T.J. Crowder Mar 18 '17 at 19:35

0 Answers0