Convert string to Title Case with JavaScript
When working with strings in JavaScript, you may come across a situation where you need to convert a string to title case. Title case is a formatting style where the first letter of each word is capitalized, while the rest of the letters are in lowercase.
Fortunately, JavaScript provides several ways to achieve this. Let’s explore a few solutions:
1. Using JavaScript’s built-in functions
One way to convert a string to title case is by utilizing JavaScript’s built-in functions like split()
and map()
. Here’s an example:
function toTitleCase(str) {
return str
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
const inputString = 'hello world';
const titleCaseString = toTitleCase(inputString);
console.log(titleCaseString);
The toTitleCase()
function takes a string as input and splits it into an array of words using the split()
function. Then, it uses the map()
function to iterate over each word and capitalize the first letter using charAt(0).toUpperCase()
. The rest of the letters are converted to lowercase using slice(1).toLowerCase()
. Finally, the words are joined back together using the join()
function.
The output of the above code will be:
Hello World
2. Using Regular Expressions
Another approach to convert a string to title case is by utilizing regular expressions. Here’s an example:
function toTitleCase(str) {
return str.replace(/bw/g, char => char.toUpperCase());
}
const inputString = 'hello world';
const titleCaseString = toTitleCase(inputString);
console.log(titleCaseString);
The toTitleCase()
function uses the replace()
function with a regular expression (/bw/g
) to match the first character of each word. The b
ensures that only the first character of each word is matched. The matched character is then converted to uppercase using toUpperCase()
.
The output of the above code will be:
Hello World
These are just a couple of ways to convert a string to title case in JavaScript. Depending on your specific requirements and preferences, you can choose the approach that suits you best.
Remember to always consider the context in which you are using the title case conversion and adapt the code accordingly. Happy coding!
Leave a Reply