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
Uncamelising a string in JavaScript
We are required to write a JavaScript function that takes in a string as the first argument and a separator character as the second argument.
The first string is guaranteed to be a camelCased string. The function should convert the case of the string by separating the words by the separator provided as the second argument.
For example −
If the input string is −
const str = 'thisIsAString'; const separator = '_';
Then the output string should be −
const output = 'this_is_a_string';
Using Custom Logic
This approach iterates through the string and identifies word boundaries by detecting uppercase letters:
const str = 'thisIsAString';
const separator = '_';
const separateCase = (str = '', separator = ' ') => {
const arr = [];
let left = 0, right = 0;
for(let i = 0; i
this_is_a_string
Using Regular Expression (Simpler Approach)
A more concise solution using regex to detect uppercase letters and replace them:
const uncamelize = (str, separator = '_') => {
return str
.replace(/([A-Z])/g, separator + '$1')
.toLowerCase()
.replace(new RegExp('^' + separator), ''); // Remove leading separator
};
console.log(uncamelize('thisIsAString', '_'));
console.log(uncamelize('camelCaseExample', '-'));
console.log(uncamelize('oneWord', '_'));
this_is_a_string
camel-case-example
one_word
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| Custom Logic | Long | Complex | Good |
| Regular Expression | Short | Simple | Excellent |
Common Use Cases
Uncamelizing strings is commonly used when:
- Converting JavaScript property names to database column names
- Generating CSS class names from camelCase variables
- Creating file names or URL slugs from camelCase strings
Conclusion
The regex approach is more concise and readable for uncamelizing strings. Use the custom logic approach when you need more control over the word detection process.
