DEV Community

Discussion on: Capitalize the first letter of every word

Collapse
 
euantorano profile image
Euan T

Another alternative would be using a regular expression, which is quite nice and compact:

function capitalize(text) {
  return text.replace(/(^[a-z]| [a-z])/g, function (match, letter) {    
    return letter.toUpperCase();
  });
}

const text = "hello world";
const capitalized = capitalize(text);

console.log(capitalized); // "Hello World"

This also turns out to be even faster in my benchmarks - this will be due to the regular expression engine being highly optimised and built into the browser. My results from the perf.link site (which doesn't seem to want to let me copy a link directly to the benchmark for some reason...) are as follows:

function ops/s %
regexCapitalize 446,440 100%
capitalize2 184,960 41%
capitalize 144,600 32%
Collapse
 
ml318097 profile image
Mehul Lakhanpal

That's awesome. Hell lot of differenceπŸ”₯