Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

camelCase to kebab-case in javascript

I have a kebabize function which converts camelCase to kebab-case. I am sharing my code. Can it be more optimized? I know this problem can be solved using regex. But, I want to do it without using regex.

const kebabize = str => {

    let subs = []
    let char = ''
    let j = 0

    for( let i = 0; i < str.length; i++ ) {

        char = str[i]

        if(str[i] === char.toUpperCase()) {
            subs.push(str.slice(j, i))
            j = i
        }

        if(i == str.length - 1) {
            subs.push(str.slice(j, str.length))
        }
    }

    return subs.map(el => (el.charAt(0).toLowerCase() + el.substr(1, el.length))).join('-')
}

kebabize('myNameIsStack')
like image 728
Stack Avatar asked Jul 27 '20 13:07

Stack


People also ask

Is camel case used in JavaScript?

camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries. Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.

How do you use a kebab case?

In contrast to camel case, kebab case separates compound words in a variable name with a dash. The dash between words can be likened to the skewer of a shish kebab, thus the name. Like snake case, which uses an underscore to separate words, kebab case maximizes whitespace in an effort to make variables easier to read.

How do you use camel case in JavaScript?

Approach: Use str. replace() method to replace the first character of string into lower case and other characters after space will be into upper case. The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively.


1 Answers

RegEx is faster!

Unlike what you might think, the RegEx way of doing this is actually significantly faster! See benchmark.

The function below supports converting both camelCase and PascalCase into kebab-case:

function toKebabCase(str) {
    return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
like image 60
Arad Avatar answered Oct 02 '22 19:10

Arad