Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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';
Example
Following is the code −
const str = 'thisIsAString';
const separator = '_';
const separateCase = (str = '', separator = ' ') => {
const arr = [];
let left = 0, right = 0;
for(let i = 0; i < str.length; i++){
const el = str[i];
const next = str[i + 1];
if((el.toUpperCase() === el && el.toUpperCase() !== el.toLowerCase()) || !next){
right = i + Number(!next);
};
if(left !== right){
const sub = str.substring(left, right).toLowerCase();
arr.push(sub);
left = right;
};
};
return arr.join(separator);
};
console.log(separateCase(str, separator));
Output
Following is the output on console −
this_is_a_string
Advertisements