Open In App

Convert string to title case in JavaScript

Last Updated : 24 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting string to title case means converting to uppercase the first letter of every word in a sentence while the other ones remain in lowercase. In this article, we will see how to convert string to title case in JavaScript

Below are the approaches to convert string to title case in JavaScript:

Approach 1: 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.

Example: In this example, we are using the above-explained method.

javascript
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'));

Output
Geeks For Geeks

Approach 2: 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. 

Example: In this example, we are using the above-explained method.

javascript
function titleCase(str) {
    str = str.toLowerCase().split(' ');
    for (let 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"));

Output
Geeks For Geeks

Approach 3: 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. 

Example: In this example, we are using the above-explained method.

javascript
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"));

Output
Converting String To Titlecase

Approach 4: 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

Example: In this example, we are using the above-explained method.

Javascript
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"));

Output
Converting String To Titlecase 

Approach 5: Using Foreach loop

In this approach, the split method is used to split the string into an array of words. Then, the forEach loop iterates over each word. Inside the loop, each word is capitalized by converting the first character to uppercase and the remaining characters to lowercase

Example: In this example, we are using the above-explained method.

Javascript
const str = "geeks for geeks";
let titleCase = "";
str.split(" ").forEach(word => {
    const capitalizedWord = word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    titleCase += capitalizedWord + " ";
});
console.log(titleCase);

Output
Geeks For Geeks 

Approach 6: Using Regular Expressions and String Split

In this approach, we utilize regular expressions along with the split() method to split the string into words, then we capitalize the first letter of each word, and finally, we join the words back together to form the title case string.

JavaScript
function titleCase(str) {
    return str.toLowerCase().replace(/(?:^|\s)\w/g, function(match) {
        return match.toUpperCase();
    });
}

console.log(titleCase("converting string to titlecase"));

Output
Converting String To Titlecase




Previous Article
Next Article

Similar Reads

How to Convert Camel Case String to Snake Case in JavaScript ?
We are going to learn about the conversion of camel case string into snake case by using JavaScript. Camel case string means words combined, each starting with uppercase and Snake case means words joined with underscores, all lowercase, Converting camel case to snake case involves transforming strings from a format where words are separated by unde
3 min read
How to convert camel case to snake case in JSON response implicitly using Node.js ?
Camel case and snake case are two common conventions for naming variables and properties in programming languages. In camel case, compound words are written with the first word in lowercase and the subsequent words capitalized, with no spaces or underscore between them. For example, firstName is written in camel case. In snake case, compound words
5 min read
How to Convert Camel Case to Snake Case in PHP ?
Given a Camel Case String, the task is to convert the Camel Case String to a Snake Case String in PHP. Examples: Input: GeeksForGeeksOutput: geeks_for_geeksInput: WelcomeToGfg Output: welcome_to_gfgCamel case uses capital letters at the beginning of each word except the first one, while snake case separates words with underscores and uses all lower
1 min read
How to convert string to camel case in JavaScript ?
We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meaning. Example of converting string to camel case in J
4 min read
How to convert a string to snake case using JavaScript ?
In this article, we are given a string in and the task is to write a JavaScript code to convert the given string into a snake case and print the modified string. Examples: Input: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_caseThere are some common approaches: Table of Content Using match(), map(),
2 min read
How to convert a string into kebab case using JavaScript ?
Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string. Examples: Input: Geeks For GeeksOutput: geeks-for-geeksInput: GeeksForGeeksOutput: geeks-for-geeksInput: Geeks_for_geeksOutput: geeks-for-geeksBelow are the approaches used to convert a string into a kebab case using
3 min read
Convert Characters of a String to Opposite Case in JavaScript
In this article, we will be converting characters of a string to opposite cases in JavaScript. We have given a string and we need to convert the string to characters in opposite case i.e. if the character is in lowercase then convert it into uppercase and vice versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput : hello every oneOutput
3 min read
How to Convert Title to URL Slug using JavaScript ?
Converting a title to a URL slug in JavaScript involves transforming the input text into a format suitable for URLs. This typically entails replacing spaces with dashes, removing special characters, and ensuring lowercase consistency for compatibility and readability in web addresses. Prerequisite HTML BasicsJavaScript BasicsBasically below program
2 min read
How to convert hyphens to camel case in JavaScript ?
Given a string containing hyphens (-) and the task is to convert hyphens (-) into camel case of a string using JavaScript. Approach: Store the string containing hyphens into a variable.Then use the RegExp to replace the hyphens and make the first letter of words upperCase. Example 1: This example converts the hyphens ('-') into camel case by using
2 min read
How to convert first letter of a string to upper case using jQuery ?
The task is to capitalize the first letter of string without using toUpperCase() method with the help of jQuery. There are two approaches that are discussed below: Approach 1: In this example, the css() method is used to set the text-transform property value to capitalize. Example: C/C++ Code &lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;titl
2 min read