如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
以下所有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()); };
其他回答
基本的方法是用匹配大写或空格的正则表达式分割字符串。然后再把碎片粘回去。技巧将处理各种方式的正则表达式分割是破坏/奇怪的浏览器。有人编写了一个库来解决这些问题;我去找找。
这是链接:http://blog.stevenlevithan.com/archives/cross-browser-split
这为我解决了这个问题,处理特殊字符和介词
export function camelize(str) {
if (!str) {
return str;
}
const preposicoes = ['da', 'de', 'di', 'do', 'du'];
return str.toLowerCase().split(' ').map(c => {
if (preposicoes.includes(c)) {
return c;
}
return `${c.substring(0, 1).toUpperCase()}${c.substring(1, c.length)}`;
}).join(' ');
}
我知道这是一个老答案,但这处理空格和_ (lodash)
function toCamelCase(s){
return s
.replace(/_/g, " ")
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");
// Both print "helloWorld"
这就是我的解决方案:
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 cammelCase(str){
let arr = str.split(' ');
let words = arr.filter(v=>v!='');
words.forEach((w, i)=>{
words[i] = w.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1);
});
});
return words.join('');
}