将任何string转换为骆驼的情况

如何使用javascript正则expression式将string转换为骆驼大小写?

EquipmentClass name equipment class nameEquipment Class Nameequipment class nameEquipment Class Name

应该全部成为: equipmentClassName

谢谢。

看看你的代码,只需要两个replace调用即可实现:

 function camelize(str) { return str.replace(/(?:^\w|[AZ]|\b\w)/g, function(letter, index) { return index == 0 ? letter.toLowerCase() : letter.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|[AZ]|\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(); }); } 

我刚刚结束这样做:

 String.prototype.toCamelCase = function(str) { return str .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); }) .replace(/\s/g, '') .replace(/^(.)/, function($1) { return $1.toLowerCase(); }); } 

我试图避免将多个replace语句链接在一起。 在我的function$ 1,$ 2,$ 3的东西。 但是这种types的分组是很难理解的,你提到的跨浏览器问题是我从来没有想过的。

在斯科特的具体情况下,我会用类似的东西:

 String.prototype.toCamelCase = function() { return this.replace(/^([AZ])|\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 

正则expression式将匹配第一个字符,如果它以大写字母开头,任何字母字符跟随一个空格,即在指定的string中2或3次。

通过将正则expression式拼写到/^([AZ])|[\s-_](\w)/g它也会使用连字符和下划线types名称。

 'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat 'underscore_name_format'.toCamelCase() // -> underscoreNameFormat 
 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, '' ); } 

我试图find一个JavaScript函数来camelCasestring,并希望确保特殊字符将被删除(我不知道什么是上面的一些答案)。 这是基于cc young的回答,增加了评论和删除了$ peci&l字符。

你可以使用这个解决scheme:

 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(''); } 

如果有人使用lodash ,则有一个_.camelCase()函数。

 _.camelCase('Foo Bar'); // → 'fooBar' _.camelCase('--foo-bar--'); // → 'fooBar' _.camelCase('__FOO_BAR__'); // → 'fooBar' 

如果不需要regexp,你可能想看看我以前很久以前用于Twinkle的代码 :

 String.prototype.toUpperCaseFirstChar = function() { return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 ); } String.prototype.toLowerCaseFirstChar = function() { return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 ); } String.prototype.toUpperCaseEachWord = function( delim ) { delim = delim ? delim : ' '; return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim ); } String.prototype.toLowerCaseEachWord = function( delim ) { delim = delim ? delim : ' '; return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim ); } 

我还没有做任何性能testing,正则expression式版本可能会或可能不会更快。

 return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) { return match.charAt(match.length-1).toUpperCase(); }); // HelloWorld 

lodash可以把握好把戏:

 var _ = require('lodash'); var result = _.camelCase('toto-ce héros') // result now contains "totoCeHeros" 

虽然lodash可能是一个“大”的库(〜4kB),但它包含了许多通常使用snippet或自己构build的函数。

我的ES6方法:

 const camelCase = str => { let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ') .reduce((result, word) => result + capitalize(word.toLowerCase())) return string.charAt(0).toLowerCase() + string.slice(1) } const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1) let baz = 'foo bar' let camel = camelCase(baz) console.log(camel) // "fooBar" camelCase('foo bar') // "fooBar" camelCase('FOO BAR') // "fooBar" camelCase('x nN foo bar') // "xNnFooBar" camelCase('!--foo-¿?-bar--121-**%') // "fooBar121" 

在@斯科特的可读方法之后,进行了一些微调

 //将任何string转换为camelCase
 var toCamelCase = function(str){
  返回str.toLowerCase()
     .replace(/ ['“] / g,'')
     .replace(/ \ W + / g,'')
     .replace(/(。)/ g,function($ 1){return $ 1.toUpperCase();})
     .replace(/ / g,'');
 }

很less修改斯科特的答案:

 toCamelCase = (string) -> string .replace /[\s|_|-](.)/g, ($1) -> $1.toUpperCase() .replace /[\s|_|-]/g, '' .replace /^(.)/, ($1) -> $1.toLowerCase() 

现在它也取代了“ – ”和“_”。

以下全部14个排列产生“equipmentClassName”的相同结果。

 String.prototype.toCamelCase = function() { return this.replace(/[^az ]/ig, '') // Replace everything but letters and spaces. .replace(/(?:^\w|[AZ]|\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()); }; 

你可以使用这个解决scheme:

 String.prototype.toCamelCase = function(){ return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();}) .replace(/(^\w)/, function($1){return $1.toLowerCase()}); }; console.log('Equipment className'.toCamelCase()); 

这个方法似乎超越了这里的大多数答案,虽然有点hacky,没有replace,没有正则expression式,只是build立一个新的string,这是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; } 

这build立在CMS的答案上,通过删除任何非字母字符, 包括下划线, \w不会删除。

 function toLowerCamelCase(str) { return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[AZ]|\b\w|\s+/g, function (match, index) { if (+match === 0 || match === '-' || match === '.' ) { return ""; // or if (/\s+/.test(match)) for white spaces } return index === 0 ? match.toLowerCase() : match.toUpperCase(); }); } toLowerCamelCase("EquipmentClass name"); toLowerCamelCase("Equipment className"); toLowerCamelCase("equipment class name"); toLowerCamelCase("Equipment Class Name"); toLowerCamelCase("Equipment-Class-Name"); toLowerCamelCase("Equipment_Class_Name"); toLowerCamelCase("Equipment.Class.Name"); toLowerCamelCase("Equipment/Class/Name"); // All output e 

上驼(“TestString”)降低骆驼大小写(“testString”),而不使用正则expression式(让我们面对它,正则expression式是邪恶的):

 'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), ''); 

我结束了一个稍微更积极的解决scheme:

 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 (comparative)
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello

基本的做法是用正则expression式匹配大写或空格来分割string。 然后你把胶片粘在一起。 窍门将处理正则expression式分裂在浏览器中被破坏/奇怪的各种方式。 有一个图书馆或者某人写了一些东西来解决这些问题。 我会找的。

这里的链接: http : //blog.stevenlevithan.com/archives/cross-browser-split

编辑 :现在在IE8中没有任何改变。

编辑 :我在什么camelCase实际上是less数(主要字符小写与大写。)。 整个社会认为一个大小写是骆驼案件,一个领先的资本是pascal案件。 我创build了两个函数,只使用正则expression式模式。 :)所以我们使用统一的词汇,我改变了我的立场,以配合大多数。


所有我相信你需要的是一个单一的正则expression式:

 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" 

要么

 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是用空格和空string交换任何非az。 这是为大写创build字边界。 “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,并将大小写不敏感标志(i)添加到模式(/ [^ AZ] / ig)。
  • 这在IE8 (srsly,谁使用IE8了)工作。使用(F12)开发工具我已经在IE11,IE10,IE9,IE8,IE7和IE5testing。 适用于所有文档模式。
  • 这将正确地处理以空白或不以空格开头的string的第一个字母。

请享用

 function convertStringToCamelCase(str){ return str.split(' ').map(function(item, index){ return index !== 0 ? item.charAt(0).toUpperCase() + item.substr(1) : item.charAt(0).toLowerCase() + item.substr(1); }).join(''); }