Convert hyphens to camel case (camelCase)

后端 未结 13 1848
梦谈多话
梦谈多话 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:15

    Another take.

    Used when...

    var string = "hyphen-delimited-to-camel-case"
    or
    var string = "snake_case_to_camel_case"
    
    
    function toCamelCase( string ){
      return string.toLowerCase().replace(/(_|-)([a-z])/g, toUpperCase );
    }
    
    function toUpperCase( string ){
      return string[1].toUpperCase();
    }
    
    Output: hyphenDelimitedToCamelCase
    
    0 讨论(0)
  • 2020-12-04 08:17
    // Turn the dash separated variable name into camelCase.
    str = str.replace(/\b-([a-z])/g, (_, char) => char.toUpperCase());
    
    0 讨论(0)
  • 2020-12-04 08:17

    Use this if you allow numbers in your string.

    Obviously the parts that begin with a number will not be capitalized, but this might be useful in some situations.

    function fromHyphenToCamelCase(str) {
      return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
    }
    

    function fromHyphenToCamelCase(str) {
      return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
    }
    
    const str1 = "category-123";
    const str2 = "111-222";
    const str3 = "a1a-b2b";
    const str4 = "aaa-2bb";
    
    console.log(`${str1} => ${fromHyphenToCamelCase(str1)}`);
    console.log(`${str2} => ${fromHyphenToCamelCase(str2)}`);
    console.log(`${str3} => ${fromHyphenToCamelCase(str3)}`);
    console.log(`${str4} => ${fromHyphenToCamelCase(str4)}`);

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

    Just a version with flag, for loop and without Regex:

    function camelCase(dash) { 
    
      var camel = false;
      var str = dash;
      var camelString = '';
    
      for(var i = 0; i < str.length; i++){
        if(str.charAt(i) === '-'){
          camel = true;
    
        } else if(camel) {
          camelString += str.charAt(i).toUpperCase();
          camel = false;
        } else {
          camelString += str.charAt(i);
        }
      } 
      return camelString;
    }
    
    0 讨论(0)
  • 2020-12-04 08:22

    Here is my implementation (just to make hands dirty)

    /**
     * kebab-case to UpperCamelCase
     * @param {String} string
     * @return {String}
     */
    function toUpperCamelCase(string) {
      return string
        .toLowerCase()
        .split('-')
        .map(it => it.charAt(0).toUpperCase() + it.substr(1))
        .join('');
    }
    
    0 讨论(0)
  • 2020-12-04 08:23

    This is one of the great utilities that Lodash offers if you are enlightened and have it included in your project.

    var str = 'my-hyphen-string';
    str = _.camelCase(str);
    // results in 'myHyphenString'
    
    0 讨论(0)
提交回复
热议问题