Skip to content
Related Articles

Related Articles

Convert string to title case in JavaScript
  • Last Updated : 23 Apr, 2019

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




<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>

OUTPUT

Geeks For Geeks

2) By using For loop to titlecase a string




<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>

OUTPUT

Geeks For Geeks

3) By using map() method




<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>

OUTPUT

Converting String To Titlecase



My Personal Notes arrow_drop_up
Recommended Articles
Page :