The Wayback Machine - https://web.archive.org/web/20240801012303/https://www.geeksforgeeks.org/how-to-convert-string-to-camel-case-in-javascript/
Open In App

How to convert string to camel case in JavaScript ?

Last Updated : 14 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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 JavaScript

Using the str.replace() method

Use the str.replace() method to replace the first character of the string in lower case and other characters after space will be in upper case. The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively.

Example 1: This example uses RegExp, toLowerCase(), and toUpperCase() methods to convert a string into camelCase. 

JavaScript
// Input string with spaces
let str = 'Click the button to convert to camelCase';

// Function to convert into camel Case
function camelCase(str) {
    // Using replace method with regEx
    return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
        return index == 0 ? word.toLowerCase() : word.toUpperCase();
    }).replace(/\s+/g, '');
}

// To display output
function gfg_Run() {
    console.log(camelCase(str));
}
// Function call
gfg_Run()

Output
clickTheButtonToConvertToCamelCase

Example 2: This example uses replace(), toLowerCase(), and toUpperCase() methods to convert a string into camelCase. 

JavaScript
let str = 'Click the button to convert to camelCase';

function camelCase(str) {
    return str
        .replace(/\s(.)/g, function (a) {
            return a.toUpperCase();
        })
        .replace(/\s/g, '')
        .replace(/^(.)/, function (b) {
            return b.toLowerCase();
        });
}

function gfg_Run() {
    console.log(camelCase(str));
}
gfg_Run()

Output
clickTheButtonToConvertToCamelCase

Using reduce() and split() method

Use reduce() method to iterate over the character of the string and convert it into camel case. The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively.

Example: This example uses reduce, toLowerCase(), and toUpperCase() methods to convert a string into camelCase. 

JavaScript
let str = 'Click the button to convert to camelCase';

function camelCase(str) {
    // converting all characters to lowercase
    let ans = str.toLowerCase();

    // Returning string to camelcase
    return ans.split(" ").reduce((s, c) => s
        + (c.charAt(0).toUpperCase() + c.slice(1)));

}

function gfg_Run() {
    console.log(camelCase(str));
}
gfg_Run()

Output
clickTheButtonToConvertToCamelcase

Using the Lodash _.camelCase() Method

In this approach, we will use the lodash _.camelCase() method which will conver the given string into the camel case.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Requiring the lodash library 
const _ = require('lodash');

// Use of _.camelCase() method
let str1 = _.camelCase("Geeks for Geeks");

// Printing the output 
console.log(str1);

// Use of _.camelCase() method
let str2 = _.camelCase("GFG-Geeks");

// Printing the output 
console.log(str2);

Output:

geeksForGeeks
gfgGeeks

Using Array.map() and Array.join()

In this approach first we split the string at hyphens (-) . Then using map() method we will iterate over each word in the array of substrings. For the first word (at index 0), no changes are made, For subsequent words, we will capitalized the first character and then concatenate with the rest of the word.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function toCamelCase(str) {
    return str
        .split(/[-_]/)
        .map((word, index) => {
            if (index === 0) {
                return word;
            }
            return (
                word.charAt(0).toUpperCase() +
                word.slice(1)
            );
        })
        .join("");
}

console.log(toCamelCase("this_is_camel_case"));

Output
thisIsCamelCase

Using a combination of String method

The combination approach converts a string to camelCase by first making it lowercase. Then, it uses a regular expression to find all instances of a dash or underscore followed by a lowercase letter, and replaces them with the uppercase version of the letter.

Example:

JavaScript
function camelCase(str) {
    // Converting all characters to lowercase
    let ans = str.toLowerCase();

    // Splitting the string by space and then mapping over each word
    // Capitalizing the first letter of each word and joining them back
    return ans.split(" ").map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() +
    word.slice(1)).join('');
}

function gfg_Run() {
    const str = 'Click the button to convert to camelCase';
    console.log(camelCase(str));
}

gfg_Run();

Output
clickTheButtonToConvertToCamelcase

Using Regex and Callback Function

The Regex and Callback Function approach uses a regular expression to match specific patterns in a string, with a callback function to handle the replacement. In this case, it replaces hyphens or underscores followed by a character with that character in uppercase, effectively converting the string to camel case.

Example: In this example The toCamelCase function converts hyphen or underscore-separated strings to camelCase by replacing these separators with uppercase letters after them, as shown in the console.log statements.

JavaScript
function toCamelCase(str) {
  return str.replace(/[-_](.)/g, (match, char) => char.toUpperCase());
}

console.log(toCamelCase('hello_world')); 
console.log(toCamelCase('foo-bar-baz')); 

Output
helloWorld
fooBarBaz




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 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 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 string to title case in JavaScript
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: Table of Content Using replace() functionUsing For
4 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
5 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: [GFGTABS] html <!DOCTYPE HTML> <html> <head> <
2 min read
Which built-in method returns the calling string value converted to upper case in JavaScript ?
The toUpperCase() built-in method returns the calling string value converted to uppercase in the javascript. This method does not affect any of the special characters, digits, and alphabets that are already in the upper case. Syntax: String.prototype.toUpperCase() Approach: This is a simple HTML file. In the body, there are two p tags one with id t
2 min read
How to change text into lower case string using filters in Vue.js ?
Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Filters are a functionality provided
2 min read
three90RightbarBannerImg