Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Hyphen string to camelCase string in JavaScript
Converting hyphen-separated strings to camelCase is a common requirement in JavaScript development. We need to transform strings like 'this-is-an-example' into 'thisIsAnExample'.
Problem Statement
Given a string with words separated by hyphens:
const str = 'this-is-an-example';
We need to convert it into camelCase format:
const output = 'thisIsAnExample';
Using split(), map(), and join() Method
The most straightforward approach splits the string by hyphens, capitalizes each word except the first, and joins them back:
const str = 'this-is-an-example';
const changeToCamel = str => {
let newStr = '';
newStr = str
.split('-')
.map((el, ind) => {
return ind && el.length ? el[0].toUpperCase() + el.substring(1) : el;
})
.join('');
return newStr;
};
console.log(changeToCamel(str));
thisIsAnExample
Using Regular Expression Method
A more concise approach uses regex to find hyphens followed by characters and replace them with uppercase characters:
const str = 'this-is-an-example';
const toCamelCase = str => {
return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
};
console.log(toCamelCase(str));
thisIsAnExample
Handling Edge Cases
A robust function should handle edge cases like empty strings, multiple consecutive hyphens, and strings without hyphens:
const toCamelCaseRobust = str => {
if (!str || typeof str !== 'string') return '';
return str
.toLowerCase()
.replace(/-+([a-z])/g, (match, letter) => letter.toUpperCase())
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
};
console.log(toCamelCaseRobust('this-is-an-example'));
console.log(toCamelCaseRobust('single-word'));
console.log(toCamelCaseRobust('--multiple--hyphens--'));
console.log(toCamelCaseRobust(''));
thisIsAnExample singleWord multipleHyphens
Comparison of Methods
| Method | Readability | Performance | Edge Case Handling |
|---|---|---|---|
| split/map/join | Good | Moderate | Basic |
| Regular Expression | Excellent | Good | Can be enhanced |
Conclusion
The regex approach is more concise and readable for converting hyphen-separated strings to camelCase. Choose the method based on your performance requirements and edge case complexity.
