Convert kebab-case to camelCase

4.4k views Asked by At

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!

4

There are 4 answers

0
Alberto Linde On

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
0
PaoloJ42 On

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;
}
0
Joop Eggen On
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.

Note that this only works with Java 9+ with the introduction of Matcher#replaceAll​(Function<MatchResult, String> replacer)

0
David Conrad On

I would use

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

You can also include a lookbehind of (?<=[a-z]) before the dash as in Pshemo's comment, if you want to only do it for dashes that come after lowercase letters instead of all instances of a dash followed by a lowercase letter, but assuming your inputs are well-formed kebab-case strings, that may not be necessary. It all depends on how you would like "-hello-world" or "HI-there" or "top10-answers" to be handled.

Note that this only works with Java 9+ with the introduction of Matcher#replaceAll​(Function<MatchResult, String> replacer)