如何使用 javascript 正则表达式将字符串转换为驼峰式大小写?
EquipmentClass name
或
Equipment className
或equipment class name
或Equipment Class Name
都应该变成: equipmentClassName
。
如何使用 javascript 正则表达式将字符串转换为驼峰式大小写?
EquipmentClass name
或
Equipment className
或equipment class name
或Equipment Class Name
都应该变成: equipmentClassName
。
查看您的代码,您只需两次replace
调用即可实现:
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"
编辑:或者通过一次replace
调用,在RegExp
.
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
如果有人使用lodash,则有一个_.camelCase()
功能。
_.camelCase('Foo Bar');
// → 'fooBar'
_.camelCase('--foo-bar--');
// → 'fooBar'
_.camelCase('__FOO_BAR__');
// → 'fooBar'
为了得到ç黄褐色的Ç ASE
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
为了获得ç黄褐色的小号entence ç ASE或P ASCAL Ç ASE
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
注意:
对于那些带有口音的语言。包括À-ÖØ-öø-ÿ
与正则表达式如下
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g
我刚刚结束了这样做:
String.prototype.toCamelCase = function(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
我试图避免将多个替换语句链接在一起。我的函数中有 1 美元、2 美元、3 美元的东西。但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的。
您可以使用此解决方案:
function toCamelCase(str){
return str.split(' ').map(function(word,index){
// If it is the first word make sure to lowercase all the chars.
if(index == 0){
return word.toLowerCase();
}
// If it is not the first word only upper case the first char and lowercase the rest.
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join('');
}