I am taking a JS course and my homework was to make a little program that camelCases values from 'textarea' input.
Dummy input:
underscore_case
first_name
Some_Variable
calculate_AGE
delayed_departure
My code looks something like this:
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function () {
const text = document.querySelector('textarea').value; //Storing data in a variable
const letsLower = text.toLowerCase(); //Lowecasing
const arrayedValues = letsLower.split('\n');
let camelCased = []; //I created an emtpy array so i could changed values to it
for (let v of arrayedValues) {
v = v.trimStart();
const up = v.indexOf('_') + 1; //Here i am detecting the character that should be changed
v = v.replace(v[up], v[up].toUpperCase()); //replacing lower to upper character
v = v.replace('_', ''); **deleting the underscore**
camelCased.push(v); //pushing the changed element to the array
}
let emoji = '';
for (let z of camelCased) {
emoji += '✔️';
console.log(`${z} ${emoji}`);
}
});
Please ignore the check emoji, this was also part of exercise.
So it works untill there is a string that has the character i want to replace earlier in the string, then it just replaces the first instance (e.g. a_a will be Aa instead of aA). I know that .replace() method replaces only the first occurrence and this the explanation of the problem.
My question is how could I re-write the program using replace method? I already know how to solve this problem in another way, as was explained in the course, but I am really curious if it can work this way.