1

I've been reviewing the answers on How to capitalize the first letter of each word in a string using JavaScript? but yet can't get any to work.

I'm trying to capitalize the first letter of each word in a string. But with an example such as I'm an example (for stack overflow). the word for is not capitalized.

Is there a way to do this?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    This in fact depends on what you will consider the start of the sentence. Does text after ( or [ or " or ' or < or { mean the start of a sentence? Will this `` also need to change to `` ? – Mohsen Alyafei Jun 25 '20 at 22:33

2 Answers2

2

You can use regex - ^([a-z])|[ (]+([a-z]) which says "every letter after a space or (. (If there are more cases, add them to the pattern)

And the code is

const result = `i'm an example (for stack overflow).`
  .replace(/^([a-z])|[ (]+([a-z])/g, l => l.toUpperCase())
  
console.log(result);

You can play with the regex here: https://regex101.com/r/gkZvyt/1

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
1

It is actually simple using regex.
Replace the ^ symbol, which means only capitalize the beginning of the sentence.
For more information and play with regex, click Here.

 const capitalize = str =>
  str.replace(/(?:\s|["([{])+\S/g, match => match.toUpperCase());
console.log(capitalize("I'm an example (for stack overflow)."));
BatshevaRich
  • 550
  • 7
  • 19