Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize Names in javascript

I have a function which Capitalize the sentences. But its not able to Capitalize names such as,

D'agostino, Fred  
D'agostino, Ralph B.  
D'allonnes, C. Revault  
D'amanda, Christopher 

I am expecting:

D'Agostino, Fred  
D'Agostino, Ralph B.  
D'Allonnes, C. Revault  
D'Amanda, Christopher 

Function:

getCapitalized(str){
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
    return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) {
      if (index > 0 && index + match.length !== title.length &&
        match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
        (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
        (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") &&
        title.charAt(index - 1).search(/[^\s-]/) < 0) {
        return match.toLowerCase();
      }
      if (match.substr(1).search(/[A-Z]|\../) > -1) {
        return match;
      }
      return match.charAt(0).toUpperCase() + match.substr(1);
    });
  }

Can anybody help me figuring out the issue? I have tried using (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") but it doesn't help.

like image 546
Vicky Gonsalves Avatar asked Aug 23 '26 00:08

Vicky Gonsalves


2 Answers

I'm not sure about all the use-cases you need to take care of, but for the question you asked, you can use regex that looks for word boundaries:

function capitalizeName(name) {
  return name.replace(/\b(\w)/g, s => s.toUpperCase());
}

console.log(capitalizeName(`D'agostino, Fred`));
console.log(capitalizeName(`D'agostino, Ralph B.`));
console.log(capitalizeName(`D'allonnes, C. Revault`));
console.log(capitalizeName(`D'amanda, Christopher`));
like image 96
KevBot Avatar answered Aug 25 '26 13:08

KevBot


I use this function to capitalize names. The parameter is usefult to force lowercase before capitalize otherwise you can get odd results (BaLlERinO, LaMbORGhini..)

It use regexp to find a space or a special character in ['`‘’.-] followed by any character not in ASCII groups 0-97 and 123-223 because there are only symbols, numbers and uppercase letters, but this characther must not be followed by another space or end of string (to avoid results like Ciccio's )

String.prototype.capitalize = function (lower) {
  return (lower ? this.toLowerCase() : this).replace(/(?:^|\s|['`‘’.-])[^\x00-\x60^\x7B-\xDF](?!(\s|$))/g, function (a) {
    return a.toUpperCase();
  });
};

console.log(" ëkthor thörsen's örst'ûber o'brian von-fist's".capitalize(true))
// Ëkthor Thörsen's Örst'Ûber O'Brian Von-Fist's
like image 36
MtwStark Avatar answered Aug 25 '26 15:08

MtwStark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!