Convert string to title case in JavaScript

We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.
This can be achieved by following ways-
1) By using replace() function

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
function sentenceCase (str) {
  if ((str===null) || (str===''))
       return false;
  else
   str = str.toString();
  
 return str.replace(/\w\S*/g, 
function(txt){return txt.charAt(0).toUpperCase() +
       txt.substr(1).toLowerCase();});
}
  
document.write(sentenceCase('geeks for geeks'));
</script>

chevron_right


OUTPUT

Geeks For Geeks

2) By using For loop to titlecase a string

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
function titleCase(str) {
  str = str.toLowerCase().split(' ');
  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); 
  }
  return str.join(' ');
}
document.write(titleCase("GEEKS FOR GEEKS"));
</script>

chevron_right


OUTPUT

Geeks For Geeks

3) By using map() method

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
function titleCase(str) {
  return str.toLowerCase().split(' ').map(function(word) {
    return (word.charAt(0).toUpperCase() + word.slice(1));
  }).join(' ');
}
document.write(titleCase("converting string to titlecase"));
</script>

chevron_right


OUTPUT

Converting String To Titlecase


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.