Convert string to title case in JavaScript
In this article, we will convert a string to a title case in such a way that every new word begins with a capital(uppercase) letter.
This can be achieved in the following ways-
- By using replace() function
- By using For loop to titlecase a string
- By using map() method
- By using reduce() method
By using replace() function: The replace() method in JavaScript is used to search a string for a value or any expression and replace it with the new value provided in the parameters. The original string is not changed by this method.
javascript
<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();}); } console.log(sentenceCase( 'geeks for geeks' )); </script> |
Output:
Geeks For Geeks
By using For loop to titlecase a string: In this method, the Javascript For loop is used to iterate over the arguments of the function and the characters are converted to Uppercase.
javascript
<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( ' ' ); } console.log(titleCase( "GEEKS FOR GEEKS" )); </script> |
Output:
Geeks For Geeks
By using map() method: The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and calling function on every element of the array.
javascript
<script> function titleCase(str) { return str.toLowerCase().split( ' ' ).map( function (word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join( ' ' ); } console.log(titleCase( "converting string to titlecase" )); </script> |
Output:
Converting String To Titlecase
By Using reduce() method: The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. But first we need to convert string into lowercase
Javascript
<script> function titleCase(st) { return st.toLowerCase().split( " " ).reduce( (s, c) => s + "" +(c.charAt(0).toUpperCase() + c.slice(1) + " " ), '' ); } console.log(titleCase( "converting string to titlecase" )); </script> |
Output:
Converting String To Titlecase
Please Login to comment...