Home > Mobile >  Convert kebab-case to camelCase
Convert kebab-case to camelCase

Time:02-04

I'm looking for a simple return inside a method that converts any use of kebab-case and turns it into camelCase.

For example:

hello-world

Becomes

helloWorld

I'm trying to use .replaceAll() but I can't seem to get it right!

CodePudding user response:

Just find the index of the - and then put the next char toUpperCase(), then remove the (-). You need to check if have more than one (-) and also check if the string don't have a (-) at the start of the sentence because u don't want this result:

Wrong: -hello-world => HelloWorld

CodePudding user response:

String kebab = "hello-world";
String camel = Pattern.compile("-(.)")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

It takes the char after the hyphen and turns it to upper-case.

CodePudding user response:

You can easily adapt these answers:

public String toCamel(String sentence) {
    sentence = sentence.toLowerCase();
    String[] words = sentence.split("-");
    String camelCase= words[0];
    for(int i=1; i<words.length; i  ){
        camelCase  = words[i].substring(0,1).toUpperCase()   words[i].substring(1);
    }
    return camelCase;
}
  •  Tags:  
  • Related