如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
这就是我的解决方案:
const toCamelWord = (word, idx) => Idx === 0 ? word.toLowerCase (): word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); const toCamelCase = text => 文本 .split (/ [_ - \] + /) . map (toCamelWord) . join (" "); console.log (toCamelCase(用户ID))
其他回答
上面的答案很简洁,但它不能处理所有的边缘情况。对于任何需要更强大的实用程序的人,没有任何外部依赖:
function camelCase(str) {
return (str.slice(0, 1).toLowerCase() + str.slice(1))
.replace(/([-_ ]){1,}/g, ' ')
.split(/[-_ ]/)
.reduce((cur, acc) => {
return cur + acc[0].toUpperCase() + acc.substring(1);
});
}
function sepCase(str, sep = '-') {
return str
.replace(/[A-Z]/g, (letter, index) => {
const lcLet = letter.toLowerCase();
return index ? sep + lcLet : lcLet;
})
.replace(/([-_ ]){1,}/g, sep)
}
// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))
// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));
// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));
演示在这里:https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark
在斯科特的具体情况下,我会这样说:
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
'EquipmentClass name'.toCamelCase() // -> equipmentClassName
'Equipment className'.toCamelCase() // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName
正则表达式将匹配以大写字母开头的第一个字符,以及空格后面的任何字母字符,即在指定的字符串中匹配2或3次。
通过将正则表达式添加到/^([A-Z])|[\s-_](\w)/g,还可以简化连字符和下划线类型的名称。
'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
编辑:现在工作在IE8没有变化。
编辑:我对camelCase到底是什么持少数意见(主角小写vs大写)。一般来说,社区认为开头小写字母是camel大小写,开头大写字母是pascal大小写。我创建了两个只使用正则表达式模式的函数。所以我们使用统一的词汇我已经改变了我的立场以配合大多数人。
我相信在这两种情况下你只需要一个正则表达式:
var camel = " THIS is camel case "
camel = $.trim(camel)
.replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
.replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
.replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); })
.replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "thisIsCamelCase"
or
var pascal = " this IS pascal case "
pascal = $.trim(pascal)
.replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
.replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
.replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); })
.replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "ThisIsPascalCase"
在函数中:你会注意到,在这些函数中,replace是将任何非a-z与空格与空字符串交换。这是为大写创建单词边界。"hello-MY#world" -> "HelloMyWorld"
// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
var retVal = '';
retVal = $.trim(str)
.replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
.replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
.replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); })
.replace(/[^A-Za-z\u00C0-\u00ff]/g, '');
return retVal
}
function toPascalCase(str) {
var retVal = '';
retVal = $.trim(str)
.replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
.replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
.replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); })
.replace(/[^A-Za-z\u00C0-\u00ff]/g, '');
return retVal
}
注:
为了可读性,我保留了A-Za-z vs为模式(/[^A-Z]/ig)添加大小写不敏感标志(I)。 这可以在IE8中工作(srsly,谁还在使用IE8呢。)使用我在IE11、IE10、IE9、IE8、IE7和IE5中测试过的(F12)开发工具。适用于所有文档模式。 这将正确地对以空格或不以空格开头的字符串的第一个字母进行大小写区分。
享受
下面是一行代码:
const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));
它根据RegExp[中提供的字符列表拆分小写字符串。\-_\s](在[]中添加更多!)并返回一个单词数组。然后,它将字符串数组缩减为一个由首字母大写的单词组成的连接字符串。由于reduce没有初始值,它将从第二个单词开始大写第一个字母。
如果你想要PascalCase,只需在reduce方法中添加一个初始空字符串,”)。
这个方法似乎比这里的大多数答案都要好,虽然有点粗糙,没有替换,没有正则表达式,只是建立一个新的字符串,那就是camelCase。
String.prototype.camelCase = function(){
var newString = '';
var lastEditedIndex;
for (var i = 0; i < this.length; i++){
if(this[i] == ' ' || this[i] == '-' || this[i] == '_'){
newString += this[i+1].toUpperCase();
lastEditedIndex = i+1;
}
else if(lastEditedIndex !== i) newString += this[i].toLowerCase();
}
return newString;
}