Convert dash-separated string to camelCase?

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

    Better do this guys,

    function camelCase(data) {
        var tmp;
        if (data && typeof data === 'object') {
            forEach(data, function (value, key) {
                var tmpvalue = camelCase(key);
                tmp[tmpvalue] = value;
            });
            return tmp;
        } else {
            return data.toLowerCase().replace(/(\_\w)/g, function (m) { return m[1].toUpperCase() }).replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
        }
    }
    
    console.log(camelCase("SucCCCess_dfds_dsqsdqs-dsdqs-dqsdqs"));

    Works perfectly in any cases.

    0 讨论(0)
  • 2020-12-24 11:43

    Yes (edited to support non-lowercase input and Unicode):

    function camelCase(input) { 
        return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
            return group1.toUpperCase();
        });
    }
    

    See more about "replace callbacks" on MDN's "Specifying a function as a parameter" documentation.

    The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).

    0 讨论(0)
  • 2020-12-24 11:44

    Here's a demo

    var test = 'It-is-a-great-day-today';
    
    function camelize(str) {
        return str[0].toLowerCase() + str.replace(/-([a-z])/g, function(a, b) {
            return b.toUpperCase();
        }).slice(1);
    }
    
    console.log(camelize(test));
    
    0 讨论(0)
  • 2020-12-24 11:45
    'it-is-a-great-day-today'.split('-').map(function(x,i){
        return (i?x[0].toUpperCase():x[0]) + x.slice(1).toLowerCase()
    }).join('')
    

    Result:

    'itIsAGreatDayToday'
    

    Alternatively, .match(/\w+/g) rather than .split('-') -- depending on what you want to do in edge cases like "this--is-a-test".

    0 讨论(0)
  • 2020-12-24 11:52

    You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):

    function camelCase(s) {
      return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
        return m.toUpperCase().replace(/-/,'');
      });
    }
    camelCase('foo-bar'); // => 'FooBar'
    camelCase('FOo-BaR-gAH'); // => 'FooBarGah'
    
    0 讨论(0)
  • 2020-12-24 11:52

    Another method using reduce:

    function camelCase(str) {
      return str
        .split('-')
        .reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
    }
    
    0 讨论(0)
提交回复
热议问题