Convert hyphens to camel case (camelCase)

后端 未结 13 1846
梦谈多话
梦谈多话 2020-12-04 08:02

With regex (i assume) or some other method, how can i convert things like:

marker-image or my-example-setting to markerImage o

相关标签:
13条回答
  • 2020-12-04 08:07

    You can use camelcase from NPM.

    npm install --save camelcase

    const camelCase = require('camelcase');
    camelCase('marker-image'); // => 'markerImage';
    camelCase('my-example-setting'); // => 'myExampleSetting';
    
    0 讨论(0)
  • 2020-12-04 08:08

    You can get the hypen and the next character and replace it with the uppercased version of the character:

    var str="marker-image-test";
    str.replace(/-([a-z])/g, function (m, w) {
        return w.toUpperCase();
    });
    
    0 讨论(0)
  • 2020-12-04 08:08

    Here is another option that combines a couple answers here and makes it method on a string:

    if (typeof String.prototype.toCamel !== 'function') {
      String.prototype.toCamel = function(){
        return this.replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
      };
    }
    

    Used like this:

    'quick_brown'.toCamel(); // quickBrown
    'quick-brown'.toCamel(); // quickBrown
    
    0 讨论(0)
  • 2020-12-04 08:10

    Try this:

    var camelCased = myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
    

    The regular expression will match the -i in marker-image and capture only the i. This is then uppercased in the callback function and replaced.

    0 讨论(0)
  • 2020-12-04 08:11

    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-04 08:11

    is also possible use indexOf with recursion for that task.

    input some-foo_sd_dsd-weqe
    output someFooSdDsdWeqe
    

    comparison ::: measure execution time for two different scripts:

    $ node camelCased.js
    someFooSdDsdWeqe
    test1: 2.986ms
    someFooSdDsdWeqe
    test2: 0.231ms
    

    code:

    console.time('test1');
    function camelCased (str) {
    
            function check(symb){
    
                let idxOf = str.indexOf(symb);
                if (idxOf === -1) {
                    return str;
                }
    
                let letter = str[idxOf+1].toUpperCase();
                str = str.replace(str.substring(idxOf+1,idxOf+2), '');
                str = str.split(symb).join(idxOf !== -1 ? letter : '');
    
                return camelCased(str);
            }       
    
            return check('_') && check('-');
    
        }
    
    console.log(camelCased ('some-foo_sd_dsd-weqe'));
    console.timeEnd('test1');
    
    
    
    console.time('test2');
    
        function camelCased (myString){
         return myString.replace(/(-|\_)([a-z])/g, function (g) { return  g[1].toUpperCase(); });
       }
    
    
    console.log(camelCased ('some-foo_sd_dsd-weqe'));
    console.timeEnd('test2');
    
    0 讨论(0)
提交回复
热议问题