How to use Regex and Callback Function In Javascript
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.
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
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 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