How to Convert String to Camel Case in JavaScript? (original) (raw)
Last Updated : 12 Aug, 2024
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.
Below are the methods to convert string to camel case in JavaScript:
Table of Content
- Using the str.replace() method
- Using reduce() and split() method
- Using the Lodash _.camelCase() Method
- Using Array.map() and Array.join()
- Using a combination of String method
- Using Regex and Callback Function
**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 = 'This string is converted 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
thisStringIsConvertedToCamelCase
**Example 2: This example uses replace(), toLowerCase(), and toUpperCase() methods to convert a string into camelCase.
JavaScript `
let str = 'This string is converted 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
thisStringIsConvertedToCamelCase
**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 = 'This string is converted 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
thisStringIsConvertedToCamelcase
**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"));
`
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