如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
function toCamelCase(str) {
// Lower cases the string
return str.toLowerCase()
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group immediately following a space
// (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
}
我试图找到一个JavaScript函数驼峰大小写字符串,并希望确保特殊字符将被删除(我有困难理解上面的一些答案正在做什么)。这是基于c c young的回答,添加了注释,并删除了$peci&l字符。
其他回答
Coderbyte Camel案例解决方案
问题:
让函数CamelCase(str)接受传入的str参数,并以适当的驼峰格式返回,其中每个单词的第一个字母都大写(不包括第一个字母)。字符串将只包含字母和分隔符标点符号的某种组合。
例如:如果str是"BOB loves-coding",那么你的程序应该返回字符串bobLovesCoding。
解决方案:
函数CamelCase(str) { 返回str .toLowerCase () .replace (/ (^ \ w) + () / g (ltr) = > ltr.toUpperCase ()) .replace (/ [^ a-zA-Z] / g,”); } //保留此函数调用 console.log(CamelCase(“猫和*狗-真棒”)); console.log(CamelCase("a b c d-e-f%g"));
在斯科特的具体情况下,我会这样说:
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
这是解决方案,包括大写的第一个字母,如果第一个字母最初是大写的。
function toCamelCase(str){
let newStr = "";
if(str){
let wordArr = str.split(/[-_]/g);
for (let i in wordArr){
if(i > 0){
newStr += wordArr[i].charAt(0).toUpperCase() + wordArr[i].slice(1);
}else{
newStr += wordArr[i]
}
}
}else{
return newStr
}
return newStr;
}
去找骆驼凯斯
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());
}
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
注意: 对于那些有口音的语言。是否包括如下的正则表达式À-ÖØ-öø- ux .replace (/ [^ a-zA-ZA-OØ- oø-y0-9) + () / g,这只是一种语言。对于另一种语言,你必须搜索和发现
我最终想出了一个稍微激进一点的解决方案:
function toCamelCase(str) {
const [first, ...acc] = str.replace(/[^\w\d]/g, ' ').split(/\s+/);
return first.toLowerCase() + acc.map(x => x.charAt(0).toUpperCase()
+ x.slice(1).toLowerCase()).join('');
}
上面的这个方法将删除所有非字母数字字符和单词的小写部分,否则将保持大写,例如。
Size (comparative) => Size比较 GDP(官方汇率)=> Hello => Hello