xvno / blog

个人博客, 不定期发布技术笔记和个人随笔.
0 stars 0 forks source link

JS: snake case & camel case #148

Open xvno opened 2 years ago

xvno commented 2 years ago

Refs

xvno commented 2 years ago

Code


// snake case => camel case
function s2c(str) {
    if('string' === typeof str) {
        return str.replace(/([-_]+(\w))/ig, (all, first, second) => {
            return second.toUpperCase();
        });
    } else {
        return str;
    }
}

// camel case => snake case
function c2s(str) {
    if('string' === typeof str) {
        return str.replace(/([A-Z])/g, (all, first) => `_${first.toLowerCase()}`);
    } else {
        return str;
    }
}