DEV Community

Riches
Riches

Posted on

Algorithm to Convert string to camel case "CodeWars"

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"));
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

Alternatively:

function camelize(text) {
  const replacement = (match, p1, p2, offset) => {
    if (p2) {
      return p2.toUpperCase();
    }
    return p1.toLowerCase();        
  }

  return text.replace(/^([A-Z])|[\s-_]+(\w)/g, replacement);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
richeskelechi profile image
Riches

Thank you so much for your contributions. Sooner or later I will start using Regex for the Algorithm. I wanted them to understand the basics and then learn how to use the advanced ones. Thank you

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

Absolutely. We are all starting from the beginning and improving our skills through the evolution of our experience.