How to convert the first letter of words into a string

9

Having a given string, how to put the first letter of each word in large letters (Uppercase)?

For example:

original: 'a música é universal' High: 'A Música É Universal'

but also names like "anna-karin" common in the Nordic countries. In this case, it should be "Anna-Karin" .

Is there a solution for all languages?

    
asked by anonymous 27.11.2014 / 20:41

2 answers

9

The solution I found, which works for most accents in Latin and German languages, was with regex:

string.replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word){
    return separator + word.charAt(0).toUpperCase() + word.slice(1);
});

In regex I try to find a character not present in this list [A-zÀ-ú] (optional, hence the ? ) and a word of one or more letters with [A-zÀ-ú]+ , both with capturing group to be able to work within the replace function.

Example:

String.prototype.capitalize = function(){
    return String(this).replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word){
        return separator + word.charAt(0).toUpperCase() + word.slice(1);
    });
}

alert('a anna-karin gosta de música!'.capitalize());
    
27.11.2014 / 20:41
2

Another possibility, created by PHP.JS staff based on PHP ucwords () function:

function ucwords(str) {
  //  discuss at: http://phpjs.org/functions/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Onno Marsman
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld');
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD');
  //   returns 2: 'HELLO WORLD'

  return (str + '')
    .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
      return $1.toUpperCase();
    });
}

Example:

function ucwords(str) {
  //  discuss at: http://phpjs.org/functions/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Onno Marsman
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld');
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD');
  //   returns 2: 'HELLO WORLD'

  return (str + '')
    .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
      return $1.toUpperCase();
    });
}

alert( ucwords( 'num ninho de mafagafos tinha sete mafagafinhos' ) );
    
28.11.2014 / 01:56