Algorithm to Convert string to camel case "CodeWars"
Riches
Posted on September 9, 2023
The Problem
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
should handle empty values
should remove underscores and convert first letter of word to upper case
should remove hyphens and convert first letter of word to upper case
Algorithm.
Step-1 - Create A Variable That will store our camel case words
Step-2 - Create a For loop that will loop through the str. on each iteration I will get the character of the letter using the index of that string.
Step-3 - Using an if statement to check if the a dash(-) or an underscore(_) was found in any of the iterations. if yes them we need to do some manipulations.
Step-4 - If any underscore or dash was found, we need to access the next value after the dash or underscore, this can be done by adding one to the current index.
Step-5 - Once we get the next character, we are to use the .toUpperCase() to convert to uppercase and then concatenate it with the variable created in step one.
Step-6 - After the concatenation we need to increase index or i by 1 (This is the variable declared in the for loop). This will enable our algorithm not to pick the next character after the underscore or dash because we have taken care of it already.
Step-7 - If no underscore or dash was found in the iteration. we just concatenate the string with the variable declared in step 1.
Step-8 - Finally we return our variable.
function toCamelCase(str){
let acceptedString = ''
for(let i = 0; i < str.length; i++){
let eachChar = str[i]
if(eachChar == '-' || eachChar == '_') {
let nextChar = str[i+1]
acceptedString += nextChar.toUpperCase()
i++
}else{
acceptedString += eachChar
}
}
return acceptedString
}
console.log(toCamelCase("the-stealth-warrior_is-Here"));
Posted on September 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.