web-dev-qa-db-fra.com

Capitaliser la première lettre de chaque mot d'une chaîne - JavaScript

Quel est le problème avec cette fonction? Je suis perdu merci pour l'aide.

function titleCase(str) {
 var splitStr = str.toLowerCase().split(' ');
 for (var i = 0; i < splitStr.length; i++) {
   if (splitStr.length[i] < splitStr.length) {
     splitStr[i].charAt(0).toUpperCase();     
   }
      str = splitStr.join(' '); 
 }
return str;
}

titleCase("I'm a little tea pot");
21
slurrr

Vous n'affectez plus vos modifications au tableau, vos efforts sont donc vains. Essaye ça:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));

57
somethinghere

Vous faites complexe une chose très facile. Vous pouvez ajouter ceci dans votre CSS:

 .capitalize {
    text-transform: capitalize;   
  }

En javascript, vous pouvez ajouter la classe à un élément

 document.getElementById("element").className="capitalize";
29
Marcos Pérez Gude

Version ES6:

const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(Word => Word.charAt(0).toUpperCase() + Word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);

18
Steve Brush

Si vous pouvez utiliser une bibliothèque tierce, alors lodash a une fonction d'assistance pour vous.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>

12
waqas

Version ES2015:

const titleCase = title => title
    .split(/ /g).map(Word => 
        `${Word.substring(0,1).toUpperCase()}${Word.substring(1)}`)
    .join("");
3
Arthur Clemens

Aussi une bonne option (surtout si vous utilisez freeCodeCamp):

function titleCase(str) {
  var wordsArray = str.toLowerCase().split(/\s+/);
  var upperCased = wordsArray.map(function(Word) {
    return Word.charAt(0).toUpperCase() + Word.substr(1);
  });
  return upperCased.join(" ");
}
3
Cheyenne Crawford

Vous pouvez simplement utiliser une fonction d'expression régulière pour modifier la capitalisation de chaque lettre. Avec les optimisations V8 JIST, ceci devrait s’avérer le plus rapide et le plus efficace en termes de mémoire.

'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|\B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})

Ou, en fonction:

var autoCaps = (function(){
    var fromCharCode = String.fromCharCode;
    return function(string){
        string.replace(/\b[a-z]|\B[A-Z]/g, function(x){
            return fromCharCode(x.charCodeAt(0)^32);
        });
    }
})();


Démo

<input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
<input id="output" type="text" readonly />
<script>
(function(){
    var fromCharCode = String.fromCharCode;
    (input.oninput = function(){
      output.value = input.value.replace(
        /\b[a-z]|\B[A-Z]/g,
        function(x){return fromCharCode(x.charCodeAt(0)^32)}
      );
    })();
})();
</script>

2
Jack Giffin

Ou peut être fait en utilisant replace (), et remplace la première lettre de chaque mot par son "upperCase". 

function titleCase(str) {
  return str.toLowerCase().split(' ').map(function(Word) {
     return Word.replace(Word[0], Word[0].toUpperCase());
      }).join(' ');
}

titleCase("I'm a little tea pot");
2
ntnbst

replace() utilisé avec RegExp

function titleCase(str) {

  var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());


console.log(newStr);

}

titleCase("I'm a little tea pot")
1
Eli Johnson

dans ES6 réponse sur une ligne en utilisant la fonction flèche

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
1
anshuman singh

Voici comment vous pouvez le faire avec la fonction map. En gros, elle fait la même chose que la réponse acceptée, mais sans le for-loop. Par conséquent, vous enregistre quelques lignes de code.

function titleCase(text) {
  if (!text) return text;
  if (typeof text !== 'string') throw "invalid argument";

  return text.toLowerCase().split(' ').map(value => {
    return value.charAt(0).toUpperCase() + value.substring(1);
  }).join(' ');
}

console.log(titleCase("I'm A little tea pot"));

1
Hamzeen Hameem

Code brut:

function capi(str) {
    var s2 = str.trim().toLowerCase().split(' ');
  var s3 = [];
  s2.forEach(function(elem, i) {
          s3.Push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));  
  });
  return s3.join(' ');
}
capi('js string exasd');
1
Chris

Cette routine gérera les mots avec trait d'union et les mots avec apostrophe. 

function titleCase(txt) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++){
    if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
    if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
    if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
        if (text.charAt(i) == "'"){
            if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1))) firstLtr = 3;
            else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2))) firstLtr = 3;
        }
    if (firstLtr == 3) firstLtr = 1;
    else firstLtr = 0;
    }
    if (firstLtr == 2){
        firstLtr = 1;
        text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
    }
    else {
        text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
    }
}

titleCase ("pAt o'Neil's"); // renvoie "Pat O'Neil's";

1
Pat

Je préfère généralement ne pas utiliser d'expression rationnelle à cause de la lisibilité et j'essaie également d'éviter les boucles. Je pense que c'est assez lisible.

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};
1
Linh Nguyen
function titleCase(str) {

var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
    var subString = myString[i].split('');
    for (var j = 0; j < subString.length; j++) {
        subString[0] = subString[0].toUpperCase();

    }
    myString[i] = subString.join('');
}

return myString.join(' '); }
1
thiagorls
text-transform: capitalize;

Css l'a eu :) 

1
JohnStone

Veuillez vérifier le code ci-dessous.

function titleCase(str) {
  var splitStr = str.toLowerCase().split(' ');
  var nstr = ""; 
  for (var i = 0; i < splitStr.length; i++) {
    nstr +=  (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + " 
    ");
  }
  console.log(nstr);
}

var strng = "this is a new demo for checking the string";
titleCase(strng);
0
Sunil Kumar
/* 1. Transform your string into lower case
2. Split your string into an array. Notice the white space i'm using for separator
3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
 - With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
 - With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
 - The "add" (+) character is for concatenate both strings. 
4. return array.join(' ') // returns the formatted array like a new string.*/


function titleCase(str){
    str = str.toLowerCase();
    var array = str.split(' ');
    for(var c = 0; c < array.length; c++){
        array[c] = array[c][0].toUpperCase() + array[c].substring(1);
    }
return array.join(' ');
}

titleCase("I'm a little tea pot");
0
Israel Calderón

La fonction ci-dessous ne modifie aucune autre partie de la chaîne que d’essayer de convertir toutes les premières lettres de tous les mots (c’est-à-dire par la définition de regex \w+) en majuscules.

Cela signifie que non ne convertit pas nécessairement les mots en Titlecase, mais fait exactement ce que le titre de la question dit: "Capitaliser la première lettre de chaque mot d'une chaîne - JavaScript"

  • Ne fends pas la ficelle
  • détermine chaque mot par l'expression régulière \w+ qui équivaut à [A-Za-z0-9_]+
    • applique la fonction String.prototype.toUpperCase() uniquement au premier caractère de chaque mot.
function first_char_to_uppercase(argument) {
  return argument.replace(/\w+/g, function(Word) {
    return Word.charAt(0).toUpperCase() + Word.slice(1);
  });
}

Exemples:

first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/

first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase

first_char_to_uppercase(
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"

first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"

first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+

first_char_to_uppercase(
  "Capitalize First Letter of each Word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"

Éditer 2019-02-07: Si vous voulez un titre réel (c'est-à-dire seulement la première lettre majuscule, tous les autres caractères minuscules):

function titlecase_all_words(argument) {
  return argument.replace(/\w+/g, function(Word) {
    return Word.charAt(0).toUpperCase() + Word.slice(1).toLowerCase();
  });
}

Exemples montrant les deux:

test_phrases = [
  "I'm a little tea pot",
  "maRy hAd a lIttLe LaMb",
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
  "…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
  "snake_case_example_.Train-case-example…",
  "Capitalize First Letter of each Word in a String - JavaScript"
];
for (el in test_phrases) {
  let phrase = test_phrases[el];
  console.log(
    phrase,
    "<- input phrase\n",
    first_char_to_uppercase(phrase),
    "<- first_char_to_uppercase\n",
    titlecase_all_words(phrase),
    "<- titlecase_all_words\n "
  );
}

// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words

// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words

// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words

// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words

// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words

// Capitalize First Letter of each Word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words
0
iolsmit

À partir de ECMA2017 ou ES8

const titleCase = (string) => {
  return string
    .split(' ')
    .map(Word => Word.substr(0,1).toUpperCase() + Word.substr(1,Word.length))
    .join(' ');
};

let result = titleCase('test test test');
console.log(result);

Explication:
1. Tout d'abord, nous passons la chaîne "test test test" à notre fonction "titleCase".
2. Nous divisons une chaîne sur la base d'espace de sorte que le résultat de la première fonction "split" sera ["test", "test", "test"]
3. Comme nous avons eu un tableau, nous avons utilisé la fonction map pour manipuler chaque mot du tableau. Nous capitalisons le premier caractère et y ajoutons le caractère restant.
4. Dans le dernier cas, nous rejoignons le tableau en utilisant l'espace lorsque nous divisons la chaîne par sapce.

0
Pulkit Aggarwal

Une réécriture plus compacte (et moderne) de la solution proposée par @ quelque chose:

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(chunk){
        return chunk.charAt(0).toUpperCase() + chunk.substring(1);
    }).join(' ');
}
    
document.write(titleCase("I'm an even smaller tea pot"));

0
Dag Sondre Hansen