Convert dash-separated string to camelCase?

后端 未结 13 1164
爱一瞬间的悲伤
爱一瞬间的悲伤 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:33

    See http://jsfiddle.net/54ZcM/

    function camelCase(string) {
        return string.toLowerCase().replace(/(\-[a-zA-Z])/g, function($1) {
            return $1.toUpperCase().replace('-','');
        })
    }
    
    alert(camelCase('fOo-BarBA-fo'));
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-24 11:35
    $scope.toCamelCase = function(arg){
        var arg = arg.toLowerCase();
        var arr = arg.split("");
        arr[0] = arr[0].toUpperCase();
        return arr.join("");
    };
    
    0 讨论(0)
  • 2020-12-24 11:37

    I know this question is a bit old but,

    Here's my version of camelCase function:

    var camelCase = (function () {
        var DEFAULT_REGEX = /[-_]+(.)?/g;
    
        function toUpper(match, group1) {
            return group1 ? group1.toUpperCase() : '';
        }
        return function (str, delimiters) {
            return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
        };
    })();
    

    It handles all of the following edge cases:

    • takes care of both underscores and hyphens by default (configurable with second parameter)
    • string with unicode characters
    • string that ends with hyphens or underscore
    • string that has consecutive hyphens or underscores

    Here's a link to live tests: http://jsfiddle.net/avKzf/2/

    Here are results from tests:

    • input: "ab-cd-ef", result: "abCdEf"
    • input: "ab-cd-ef-", result: "abCdEf"
    • input: "ab-cd-ef--", result: "abCdEf"
    • input: "ab-cd--ef--", result: "abCdEf"
    • input: "--ab-cd--ef--", result: "AbCdEf"
    • input: "--ab-cd-__-ef--", result: "AbCdEf"

    Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:

    function lcfirst(str) {
        return str && str.charAt(0).toLowerCase() + str.substring(1);
    }
    
    0 讨论(0)
  • 2020-12-24 11:39
    var string = "it-is-a-great-day-today";
    or
    var string = "it_is_a_great_day_today";
    
    var regex = /(_|-)([a-z])/g;
    
    string.toLowerCase().replace(regex, toCamelCase );
    
    function toCamelCase( string ){
      return string[1].toUpperCase();
    }
    
    Output: "itIsAGreatDayToday";
    
    0 讨论(0)
  • 2020-12-24 11:41

    This should also work:

    function camelCase(str) {
      return str.replace(/^.|-./g, function(letter, index) {
        return index == 0 ? letter.toLowerCase() : letter.substr(1).toUpperCase();
      });
    }
    

    And IMHO it is little bit more efficient since we're not converting whole input string to lowercase first and then convert to uppercase if needed. This function only converts first letter to lowercase and then every character after hyphen - to uppercase.

    0 讨论(0)
提交回复
热议问题