Convert dash-separated string to camelCase?

后端 未结 13 1232
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 11:01

For example suppose I always have a string that is delimited by \"-\". Is there a way to transform

it-is-a-great-day-today

to

itIsAGreatDayToday

13条回答
  •  眼角桃花
    2020-12-24 11:34

    This works great but someone might be able to clean it up.

    var toCamelCase = function(str) {
            // Replace special characters with a space
            str = str.replace(/[^a-zA-Z0-9 ]/g, " ");
            // put a space before an uppercase letter
            str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');
            // Lower case first character and some other stuff that I don't understand
            str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();
            // uppercase characters preceded by a space or number
            str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function(a,b,c) {
                return b.trim() + c.toUpperCase();
            });
            return str;
    };
    
    console.log(toCamelCase('hyphen~name~ format'));
    console.log(toCamelCase('hyphen.name.format'));
    console.log(toCamelCase('hyphen-name-format'));
    console.log(toCamelCase('Hyphen-Dame-Gormat'));
    console.log(toCamelCase('EquipmentClass name'));
    console.log(toCamelCase('Equipment className'));
    console.log(toCamelCase('equipment class name'));
    console.log(toCamelCase(' e    Equipment Class Name'));
    console.log(toCamelCase('under9score_name_format'));
    console.log(toCamelCase('Enderscore_name_format'));
    console.log(toCamelCase('EnderscoreBameFormat'));
    console.log(toCamelCase('_EnderscoreBameFormat'));
    

    http://jsbin.com/yageqi/1/edit?js,console

提交回复
热议问题