Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript capitalize first letter of each word in a string only if lengh > 2

I looked at some questions and answers about capitalize in StackOverflow but could not find answer about my problem.

I would like to capitalize first letter of each word in a string only if word lengh > 2.

My temporary solution was:

var str =  str.toLowerCase().replace(/\b[a-z]/g, function (letter) {
                return letter.toUpperCase();
            }).replace(/\b\w{1,2}\b/g, function (letter) {
                return letter.toLowerCase();
            });

There is a solution that can unite the two regex in one?

like image 858
Conrado Fonseca Avatar asked Jun 19 '13 20:06

Conrado Fonseca


1 Answers

Here's a simpler solution which does the job.

const capitalize = (str) =>
  str.toLowerCase().replace(/\w{3,}/g, (match) =>
    match.replace(/\w/, (m) => m.toUpperCase()));
like image 85
Hitesh Kumar Avatar answered Oct 20 '22 22:10

Hitesh Kumar