简体   繁体   English

将连字符转换为驼峰式 (camelCase)

[英]Convert hyphens to camel case (camelCase)

With regex (i assume) or some other method, how can i convert things like:使用正则表达式(我假设)或其他方法,我如何转换如下内容:

marker-image or my-example-setting to markerImage or myExampleSetting . marker-imagemy-example-settingmarkerImagemyExampleSetting

I was thinking about just splitting by - then convert the index of that hypen +1 to uppercase.我正在考虑只是拆分-然后将该连字符 +1 的索引转换为大写。 But it seems pretty dirty and was hoping for some help with regex that could make the code cleaner.但它看起来很脏,希望对正则表达式有一些帮助,可以使代码更干净。

No jQuery...没有jQuery...

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 .正则表达式将匹配marker-image中的-i并仅捕获i This is then uppercased in the callback function and replaced.然后在回调 function 中将其大写并替换。

This is one of the great utilities that Lodash offers if you are enlightened and have it included in your project.这是Lodash提供的很棒的实用程序之一,如果您开明并且将其包含在您的项目中。

var str = 'my-hyphen-string';
str = _.camelCase(str);
// results in 'myHyphenString'

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();
});

Here's my version of camelCase function:这是我的骆驼案例 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带有 unicode 字符的字符串
  • 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/这是现场测试的链接: http://jsfiddle.net/avKzf/2/

Here are results from tests:以下是测试结果:

  • input: "ab-cd-ef", result: "abCdEf"输入:“ab-cd-ef”,结果:“abCdEf”
  • input: "ab-cd-ef-", result: "abCdEf"输入:“ab-cd-ef-”,结果:“abCdEf”
  • input: "ab-cd-ef--", result: "abCdEf"输入:“ab-cd-ef--”,结果:“abCdEf”
  • input: "ab-cd--ef--", result: "abCdEf"输入:“ab-cd--ef--”,结果:“abCdEf”
  • input: "--ab-cd--ef--", result: "AbCdEf"输入:“--ab-cd--ef--”,结果:“AbCdEf”
  • input: "--ab-cd-__-ef--", result: "AbCdEf"输入:“--ab-cd-__-ef--”,结果:“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.如果这不是您所期望的,您始终可以使用 lcfirst。 Here's my lcfirst if you need it:如果您需要,这是我的 lcfirst:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}

This doesn't scream out for a RegExp to me.这对我来说并不需要RegExp Personally I try to avoid regular expressions when simple string and array methods will suffice:当简单的字符串和数组方法就足够时,我个人会尽量避免使用正则表达式:

let upFirst = word => 
  word[0].toUpperCase() + word.toLowerCase().slice(1)

let camelize = text => {
  let words = text.split(/[-_]/g) // ok one simple regexp.
  return words[0].toLowerCase() + words.slice(1).map(upFirst)
}

camelize('marker-image') // markerImage

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
// Turn the dash separated variable name into camelCase.
str = str.replace(/\b-([a-z])/g, (_, char) => char.toUpperCase());

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('');
}

You can use camelcase from NPM.您可以使用NPM的驼峰式。

npm install --save camelcase

const camelCase = require('camelcase');
camelCase('marker-image'); // => 'markerImage';
camelCase('my-example-setting'); // => 'myExampleSetting';

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

is also possible use indexOf with recursion for that task.也可以将 indexOf 与递归一起用于该任务。

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');

Just a version with flag, for loop and without Regex:只是一个带有标志、for循环且没有正则表达式的版本:

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;
}

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)}`);

Use String 's replace() method with a regular expression literal and a replacement function.Stringreplace()方法与正则表达式文字和替换 function 一起使用。

For example:例如:

'uno-due-tre'.replace(/-./g, (m) => m[1].toUpperCase()) // --> 'unoDueTre'

Explanation:解释:

  • 'uno-due-tre' is the (input) string that you want to convert to camel case. 'uno-due-tre'是要转换为驼峰式大小写的(输入)字符串。
  • /-./g (the first argument passed to replace() ) is a regular expression literal. /-./g (传递给replace()的第一个参数)是正则表达式文字。
    • The '-.' '-.' (between the slashes) is a pattern. (斜线之间)是一种模式。 It matches a single '-' character followed by any single character.它匹配单个'-'字符后跟任何单个字符。 So for the string 'uno-due-tre' , the pattern '-.'所以对于字符串'uno-due-tre' ,模式'-.' matches '-d' and '-t' .匹配'-d''-t'
    • The 'g' (after the closing slash) is a flag. 'g' (在斜线之后)是一个标志。 It stands for "global" and tells replace() to perform a global search and replace, ie, to replace all matches, not just the first one.它代表“全局”并告诉replace()执行全局搜索和替换,即替换所有匹配项,而不仅仅是第一个匹配项。
  • (m) => m[1].toUpperCase() (the second argument passed to replace() ) is the replacement function. (m) => m[1].toUpperCase() (传递给replace()的第二个参数)是替换 function。 It's called once for each match.每场比赛调用一次。 Each matched substring is replaced by the string this function returns.每个匹配的 substring 都被 function 返回的字符串替换。 m (the first argument of this function) represents the matched substring. m (此函数的第一个参数)表示匹配的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ。 This function returns the second character of m uppercased.这个 function 返回m的第二个字符大写。 So when m is '-d' , this function returns 'D' .所以当m'-d'时,这个 function 返回'D'
  • 'unoDueTre' is the new (output) string returned by replace() . 'unoDueTre'replace()返回的新(输出)字符串。 The input string is left unchanged.输入字符串保持不变。

You can also use string and array methods;您还可以使用字符串和数组方法; I used trim to avoid any spaces.我使用修剪来避免任何空格。

const properCamel = (str) =>{

  const lowerTrim = str.trim().toLowerCase(); 

  const array = lowerTrim.split('-');

  const firstWord = array.shift();

  const caps = array.map(word=>{

    return word[0].toUpperCase() + word.slice(1);

  })

  caps.unshift(firstWord)

  return caps.join('');

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM