如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
去找骆驼凯斯
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) {
// 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字符。
以下所有14个排列产生相同的“equipmentClassName”结果。
String.prototype.toCamelCase = function() { return this.replace(/[^a-z ]/ig, '') // Replace everything but letters and spaces. .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, // Find non-words, uppercase letters, leading-word letters, and multiple spaces. function(match, index) { return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase'](); }); } String.toCamelCase = function(str) { return str.toCamelCase(); } var testCases = [ "equipment class name", "equipment class Name", "equipment Class name", "equipment Class Name", "Equipment class name", "Equipment class Name", "Equipment Class name", "Equipment Class Name", "equipment className", "equipment ClassName", "Equipment ClassName", "equipmentClass name", "equipmentClass Name", "EquipmentClass Name" ]; for (var i = 0; i < testCases.length; i++) { console.log(testCases[i].toCamelCase()); };
我最终想出了一个稍微激进一点的解决方案:
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
return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld
从上驼峰格式("TestString")到下驼峰格式("TestString"),而不使用正则表达式(让我们面对现实吧,正则表达式是邪恶的):
'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');