Convert any string to a camel body

How to convert string to camel case using javascript regex?

EquipmentClass name or Equipment className or equipment class name or equipment class name

everyone should become: equipmentClassName .

+136
javascript regex camelcasing
Jun 03 '10 at 23:30
source share
31 answers
  • one
  • 2

I just finished this:

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

I tried to avoid combining multiple replacement statements. Something where I will have $ 1, $ 2, $ 3 in my function. But this type of grouping is hard to understand, and your mention of cross-browser issues is something I never thought about.

+46
Jun 03 '10 at 23:46
source share

Looking at your code, you can achieve it with just two replace calls:

 function camelize(str) { return str.replace(/(?:^\w|[AZ]|\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" 

Edit: Or with a single replace call, capturing spaces is also in 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(); }); } 
+202
Jun 04 2018-10-06T00:
source share

If someone uses lodash , there is _.camelCase() .

 _.camelCase('Foo Bar'); //'fooBar' _.camelCase('--foo-bar--'); //'fooBar' _.camelCase('__FOO_BAR__'); //'fooBar' 
+78
May 05 '16 at 2:15
source share

You can use this solution:

 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(''); } 
+36
Mar 13 '16 at 22:41
source share

In a specific case, Id Scott goes something like:

 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 

A regular expression will match the first character if it starts with a capital letter and any alphabetical character following a space, i.e. 2 or 3 times in the specified lines.

By expressing the regular expression before /^([AZ])|[\s-_](\w)/g it will also display hyphen and underscore type names.

 'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat 'underscore_name_format'.toCamelCase() // -> underscoreNameFormat 
+25
Apr 05 '13 at 8:54
source share
 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, '' ); } 

I tried to find the JavaScript function for the camelCase string and wanted to make sure that the special characters would be removed (and it was difficult for me to understand what some of the above answers did). This is based on cc junior answer by adding comments and removing $ peci & l characters.

+21
Sep 16 '15 at 9:02
source share

In order to get with Amel C aza

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


Get C amel S entence C ase or P ascal C ase

 var camelSentence = function camelSentence(str) { return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr) { return chr.toUpperCase(); }); } 

Remarks:
For those with accented language. Include À-ÖØ-öø-ÿ in the regular expression as follows
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g

+20
Sep 28 '18 at 9:05
source share

If regexp is not required, you can see the following code I made a long time ago for 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 ); } 

I have not tested performance, and regular expression versions may or may not be faster.

+9
Jun 04 2018-10-10T00:
source share

My ES6 approach:

 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" 
+7
Aug 02 '17 at 12:45
source share

lodash can do the trick confidently and well:

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

Although lodash may be a "large" library (~ 4kB), it contains many features that you usually use to create fragments or create yourself.

+5
Jul 29 '16 at 13:37
source share

Here is one liner doing the job:

 const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1)); 

It breaks the string in lowercase based on the list of characters represented in RegExp [.\-_\s] (add more to []!), And returns an array of words. He then shrinks the array of strings to one concatenated string of words with first capital letters. Since the abbreviation does not have an initial meaning, it will start with capital letters the first letters starting with the second word.

If you want PascalCase, just add the starting blank line ,'') to the Reduce method.

+5
Jun 18 '18 at 10:19
source share
 return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) { return match.charAt(match.length-1).toUpperCase(); }); // HelloWorld 
+4
Mar 07 '17 at 10:33
source share

after @Scott's readable approach, a little tweaking

 // convert any string to camelCase
 var toCamelCase = function (str) {
   return str.toLowerCase ()
     .replace (/ ['']] / g, '')
     .replace (/ \ W + / g, '')
     .replace (/ (.) / g, function ($ 1) {return $ 1.toUpperCase ();})
     .replace (/ / g, '');
 }
+3
Nov 02
source share

All 14 permutations below produce the same "equipmentClassName" result.

 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()); }; 
+3
Sep 14 '15 at 11:04
source share

you can use this solution:

 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()); 
+3
May 14 '16 at 9:03
source share

Scott's slightly modified answer:

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

now it replaces "-" and "_" too.

+2
Jul 27 '15 at 13:10
source share

There is my solution:

 const toCamelWord = (word, idx) => idx === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); const toCamelCase = text => text .split(/[_-\s]+/) .map(toCamelWord) .join(""); console.log(toCamelCase('User ID')) 
+2
May 22 '18 at 11:54
source share

This method seems to be superior to most of the answers here, it is a bit hacked, although it doesn’t replace, doesn’t have a regular expression, it just creates a new line, which is 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; } 
+1
Jan 21 '16 at 11:01
source share

This is based on the CMS response, removing any non-alphanumeric characters , including underscores, which \w does not remove.

 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 
+1
Mar 18 '16 at 9:39
source share

Upper camel case ("TestString") for the bottom of the camel ("testString") without using a regular expression (let it look, the regular expression is evil):

 'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), ''); 
+1
May 10 '17 at 9:54 a.m.
source share

I ended up developing a slightly more aggressive solution:

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

This one, above, will remove all non-alphanumeric characters and lowercase parts of words that would otherwise remain in uppercase, for example.

  • Size (comparative) => sizeComparative
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello
+1
Jul 11 '17 at 8:59
source share
 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(''); } 
+1
Oct 17 '17 at 18:14
source share

Because this question needs another answer ...

I tried several previous solutions, and all of them had one or another drawback. Some have not removed punctuation; some did not handle case numbers; some did not handle multiple punctuation marks in a row.

None of them handled a string like a1 2b . There is no explicit agreement for this case, but some other questions about the stack flow suggested separating numbers with underscores.

I doubt this is the most efficient answer (three lines go through a line, not one or two), but it goes through all the tests I can think of. Honestly, I really can’t imagine the case when you make so many camel conversions that performance will matter.

(I added this as an npm package . It also includes an optional boolean parameter to return a Pascal Case instead of a Camel Case.)

 const underscoreRegex = /(?:[^\w\s]|_)+/g, sandwichNumberRegex = /(\d)\s+(?=\d)/g, camelCaseRegex = /(?:^\s*\w|\b\w|\W+)/g; String.prototype.toCamelCase = function() { if (/^\s*_[\s_]*$/g.test(this)) { return '_'; } return this.replace(underscoreRegex, ' ') .replace(sandwichNumberRegex, '$1_') .replace(camelCaseRegex, function(match, index) { if (/^\W+$/.test(match)) { return ''; } return index == 0 ? match.trimLeft().toLowerCase() : match.toUpperCase(); }); } 

Test Cases (Jest)

 test('Basic strings', () => { expect(''.toCamelCase()).toBe(''); expect('AB C'.toCamelCase()).toBe('aBC'); expect('aB c'.toCamelCase()).toBe('aBC'); expect('abc def'.toCamelCase()).toBe('abcDef'); expect('abc__ _ _def'.toCamelCase()).toBe('abcDef'); expect('abc__ _ d_ e _ _fg'.toCamelCase()).toBe('abcDEFg'); }); test('Basic strings with punctuation', () => { expect('a'b--d -- f.h'.toCamelCase()).toBe('aBDFH'); expect('...a...def'.toCamelCase()).toBe('aDef'); }); test('Strings with numbers', () => { expect('12 3 4 5'.toCamelCase()).toBe('12_3_4_5'); expect('12 3 abc'.toCamelCase()).toBe('12_3Abc'); expect('ab2c'.toCamelCase()).toBe('ab2c'); expect('1abc'.toCamelCase()).toBe('1abc'); expect('1Abc'.toCamelCase()).toBe('1Abc'); expect('abc 2def'.toCamelCase()).toBe('abc2def'); expect('abc-2def'.toCamelCase()).toBe('abc2def'); expect('abc_2def'.toCamelCase()).toBe('abc2def'); expect('abc1_2def'.toCamelCase()).toBe('abc1_2def'); expect('abc1 2def'.toCamelCase()).toBe('abc1_2def'); expect('abc1 2 3def'.toCamelCase()).toBe('abc1_2_3def'); }); test('Oddball cases', () => { expect('_'.toCamelCase()).toBe('_'); expect('__'.toCamelCase()).toBe('_'); expect('_ _'.toCamelCase()).toBe('_'); expect('\t_ _\n'.toCamelCase()).toBe('_'); expect('_a_'.toCamelCase()).toBe('a'); expect('\''.toCamelCase()).toBe(''); expect('\tab\tcd'.toCamelCase()).toBe('abCd'); expect(' ab\tcd\r -_ |'ef'.toCamelCase()).toBe('abCdEf'); }); 
+1
Oct 11 '18 at 3:07
source share

Here is my suggestion:

 function toCamelCase(string) { return '${string}' .replace(new RegExp(/[-_]+/, 'g'), ' ') .replace(new RegExp(/[^\w\s]/, 'g'), '') .replace( new RegExp(/\s+(.)(\w+)/, 'g'), ($1, $2, $3) => '${$2.toUpperCase() + $3.toLowerCase()}' ) .replace(new RegExp(/\s/, 'g'), '') .replace(new RegExp(/\w/), s => s.toLowerCase()); } 

or

 String.prototype.toCamelCase = function() { return this .replace(new RegExp(/[-_]+/, 'g'), ' ') .replace(new RegExp(/[^\w\s]/, 'g'), '') .replace( new RegExp(/\s+(.)(\w+)/, 'g'), ($1, $2, $3) => '${$2.toUpperCase() + $3.toLowerCase()}' ) .replace(new RegExp(/\s/, 'g'), '') .replace(new RegExp(/\w/), s => s.toLowerCase()); }; 

Test cases:

 describe('String to camel case', function() { it('should return a camel cased string', function() { chai.assert.equal(toCamelCase('foo bar'), 'fooBar'); chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar'); chai.assert.equal(toCamelCase('fooBar'), 'fooBar'); chai.assert.equal(toCamelCase('FooBar'), 'fooBar'); chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar'); chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar'); chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121'); }); }); 
+1
Dec 28 '18 at 1:46
source share

I know this is an old answer, but it handles spaces and _ (lodash)

 function toCamelCase(s){ return s .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" 
+1
Jul 16 '19 at 15:11
source share

A basic approach would be to split the string into uppercase or spaces with a regular expression. Then you glue the pieces back together. Trick will deal with various ways of decomposing regular expressions broken / weird in browsers. There is a library or something that someone wrote to fix these problems; I will look for him.

here's the link: http://blog.stevenlevithan.com/archives/cross-browser-split

0
Jun 03 2018-10-10T00:
source share

EDIT : Now works in IE8 unchanged.

EDIT . I was in the minority about what camelCase (leading character in lowercase and uppercase) is actually. The community as a whole believes that the leading lowercase is the case of a camel, and the leading capital is pascal. I created two functions that use only regex patterns. :) So, we use a single dictionary, which I changed to fit most.




All that seems necessary to me is one regular expression anyway:

 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" 

or

 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" 

In functions: you will notice that in these functions the replacement replaces any non -zz with a space vs an empty string. This is done to create word boundaries for capitalization. "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 } 

Notes:

  • I left A-Za-z against adding a case insensitive flag (i) to the pattern (/ [^ AZ] / ig) for readability.
  • This works in IE8 (srsly, which uses IE8 more.) Using the (F12) dev tools I tested in IE11, IE10, IE9, IE8, IE7 and IE5. It works in all document modes.
  • This will be true in the case of the first letter of lines starting with or without spaces.

Enjoy

0
Dec 18 '16 at 19:44
source share

I think this should work ..

 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(''); } 
0
Aug 17 '18 at 6:17
source share

Super easy way using the turboCommons library:

 npm install turbocommons-es5 <script src="turbocommons-es5/turbocommons-es5.js"></script> <script> var StringUtils = org_turbocommons.StringUtils; console.log(StringUtils.formatCase('EquipmentClass', StringUtils.FORMAT_LOWER_CAMEL_CASE)); console.log(StringUtils.formatCase('Equipment className', StringUtils.FORMAT_LOWER_CAMEL_CASE)); console.log(StringUtils.formatCase('equipment class name', StringUtils.FORMAT_LOWER_CAMEL_CASE)); console.log(StringUtils.formatCase('Equipment Class Name', StringUtils.FORMAT_LOWER_CAMEL_CASE)); </script> 

You can also use StringUtils.FORMAT_CAMEL_CASE and StringUtils.FORMAT_UPPER_CAMEL_CASE to generate first-letter variants.

More info here:

Convert string to CamelCase, UpperCamelCase or lowerCamelCase

0
Nov 04 '18 at 9:29
source share

Do not use String.prototype.toCamelCase () because String.prototypes is read-only, most js compilers give this warning.

Like me, those who know that a string will always contain only one space can use a simpler approach:

 let name = 'test string'; let pieces = name.split(' '); pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1)); return pieces.join(''); 

Have a nice day. :)

0
Jan 21 '19 at 4:41
source share
  • one
  • 2



All Articles