駝峰命名與下劃線相互轉(zhuǎn)換

js將下劃線命名與駝峰式命名相互轉(zhuǎn)換

駝峰

下劃線

下劃線轉(zhuǎn)駝峰式命名


// 字符串的下劃線格式轉(zhuǎn)駝峰格式,eg:hello_world => helloWorld
function underline2Hump(s) {
    return s.replace(/_(\w)/g, function (all, letter) {
        return letter.toUpperCase()
    })
}

// JSON對象的key值轉(zhuǎn)換為駝峰式
function jsonToHump(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            jsonToHump(v)
        })
    } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function (key) {
            var newKey = underline2Hump(key)
            if (newKey !== key) {
                obj[newKey] = obj[key]
                delete obj[key]
            }
            jsonToHump(obj[newKey])
        })
    }
    return obj
}

駝峰式命名轉(zhuǎn)換為下劃線


// 字符串的駝峰格式轉(zhuǎn)下劃線格式,eg:helloWorld => hello_world
function hump2Underline(s) {
    return s.replace(/([A-Z])/g, '_$1').toLowerCase()
}


// JSON對象的key值轉(zhuǎn)換為下劃線格式
function jsonToUnderline(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            jsonToUnderline(v)
        })
    } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function (key) {
            var newKey = hump2Underline(key)
            if (newKey !== key) {
                obj[newKey] = obj[key]
                delete obj[key]
            }
            jsonToUnderline(obj[newKey])
        })
    }
    return obj
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容