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
Convert hyphens to camel case (camelCase)
提问by Oscar Godson
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-image
或者my-example-setting
到markerImage
或myExampleSetting
。
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 -i
in marker-image
and capture only the i
. This is then uppercased in the callback function and replaced.
正则表达式将匹配-i
inmarker-image
并仅捕获i
. 然后在回调函数中将其大写并替换。
回答by ShadeTreeDeveloper
回答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 RegExp
to 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
回答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;
}