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
<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
filter_none
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> |
chevron_right
filter_none
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> |
chevron_right
filter_none
OUTPUT
Converting String To Titlecase
Recommended Posts:
- How to convert string to camel case in JavaScript ?
- How to convert hyphens to camel case in JavaScript ?
- JavaScript | Convert a string to boolean
- How to convert an object to string using JavaScript?
- Convert string into date using JavaScript
- How to convert string into float in JavaScript?
- Convert a string to an integer in JavaScript
- How to Convert JS Object to JSON String in JQuery/Javascript?
- Convert comma separated string to array using JavaScript
- JavaScript | Convert bytes to human-readable string
- How to convert seconds to time string format hh:mm:ss using JavaScript ?
- How to convert a currency string to a double value with jQuery or Javascript?
- Switch Case in JavaScript
- Case insensitive search in JavaScript
- Compare the Case Insensitive strings in JavaScript
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.



