Javascript 将连字符转换为驼峰式大小写 (camelCase)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6660977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:41:51  来源:igfitidea点击:

Convert hyphens to camel case (camelCase)

javascriptregexcamelcasing

提问by Oscar Godson

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

使用正则表达式(我假设)或其他一些方法,我如何转换如下内容:

marker-imageor my-example-settingto markerImageor myExampleSetting.

marker-image或者my-example-settingmarkerImagemyExampleSetting

I was thinking about just splitting by -then convert the index of that hypen +1 to uppercase. But it seems pretty dirty and was hoping for some help with regex that could make the code cleaner.

我正在考虑只是拆分-然后将该连字符 +1 的索引转换为大写。但它看起来很脏,希望得到一些关于正则表达式的帮助,可以使代码更清晰。

NojQuery...

没有jQuery...

回答by

Try this:

尝试这个:

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

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

正则表达式将匹配-iinmarker-image并仅捕获i. 然后在回调函数中将其大写并替换。

回答by ShadeTreeDeveloper

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

如果您受到启发并将其包含在您的项目中,那么这是Lodash提供的重要实用程序之一。

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

回答by mck89

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

回答by Joon

Here's my version of camelCase function:

这是我的camelCase函数版本:

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
  • 默认情况下同时处理下划线和连字符(可使用第二个参数配置)
  • 带有 unicode 字符的字符串
  • 以连字符或下划线结尾的字符串
  • 具有连续连字符或下划线的字符串

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"
  • 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"
  • 输入:“ab-cd-ef”,结果:“abCdEf”
  • 输入:“ab-cd-ef-”,结果:“abCdEf”
  • 输入:“ab-cd-ef--”,结果:“abCdEf”
  • 输入:“ab-cd--ef--”,结果:“abCdEf”
  • 输入:“--ab-cd--ef--”,结果:“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. Here's my lcfirst if you need it:

请注意,以分隔符开头的字符串将导致以大写字母开头。如果这不是您所期望的,您可以随时使用 lcfirst。如果您需要,这是我的 lcfirst:

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

回答by Joon

This doesn't scream out for a RegExpto me. Personally I try to avoid regular expressions when simple string and array methods will suffice:

RegExp对我来说并没有尖叫。就我个人而言,当简单的字符串和数组方法就足够时,我会尽量避免使用正则表达式:

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

回答by John Naegle

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

回答by alex

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

回答by Lanil Marasinghe

You can use camelcasefrom NPM.

您可以使用NPM 中的驼峰命名法

npm install --save camelcase

npm install --save camelcase

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

回答by SoEzPz

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

回答by Hunter

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