将下划线命名转小驼峰大驼峰命名

东明兄 2019-06-16
0条评论 1,744 次浏览
东明兄 2019-06-160条评论 1,744 次浏览
    function toCamel(str, type) {
        var arr = [];
        arr = str.split("");
        var res = arr.map((item, index) => {
            if (item === '_') {
                item = "";
                if (arr[index + 1]) arr[index + 1] = arr[index + 1].toLocaleUpperCase();
            }
            return item;
        });
        var resStr = res.join("");
        switch (type) {
            case 'small':
                resStr = resStr.replace(resStr[0], resStr[0].toLocaleLowerCase());//首字母转小写
                break;
            case 'big':
                resStr = resStr.replace(resStr[0], resStr[0].toLocaleUpperCase());//首字母转大写
                break;
            default:
                throw "转换类型错误 仅限 small  big"
        }
        return resStr;
    }
    console.log("小驼峰", toCamel("user_name", "small"));//小驼峰
    console.log("大驼峰", toCamel("user_name", "big"));//大驼峰

demo演示地址:http://demo.crazyming.com/?link=topic/d4/下划线命名转驼峰.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注