Converting a string with spaces into camel case
Asked Answered
E

45

299

How can I convert a string into camel case using javascript regex?

EquipmentClass name or Equipment className or equipment class name or Equipment Class Name

should all become: equipmentClassName.

Ellerey answered 3/6, 2010 at 23:30 Comment(2)
I made a jsperf test of the various methods. the results were slightly inconclusive. it seems to depend on the input string.Flautist
A new jsperf test with a few different strings to test and a wider variety of implementations: jsperf.com/camel-casing-regexp-or-character-manipulation/1 -- this leads me to the conclusion that for the average case, despite the asker's phrasing of this question, regular expressions are not what you want. Not only are they much harder to understand, they also (at least for current versions of Chrome) take about twice as long to run.Binnie
E
72

I just ended up doing 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 was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.

Ellerey answered 3/6, 2010 at 23:46 Comment(8)
That looks fine to me, and nothing looks suspicious as far as cross-browser issues. (Not that I'm a super-expert or anything.)Rectangular
If you're going to use the String.prototype, why not just use 'this' instead of sending a 'str' parameter?Flautist
Doesn't works in Safari. > "very active".toCamelCase() < TypeError: undefined is not an object (evaluating 'str .replace')Filiform
For better browser compatibility please use this instead of str (and remove the parameter from the function call)Filiform
You just need to use this.valueOf() instead of passing str. Alternatively (as in my case) this.toLowerCase() as my input strings were in ALL CAPS which didn't have the non-hump portions lowercased properly. Using just this returns the string object itself, which is actually an array of char, hence the TypeError mentioned above.Sickly
This returns the exact opposite of what's needed. This'll return sTRING.Gynaecology
Scott Klarenbach, Thank you for good solution. It just doesn't work if there are 2 whitespaces between words: toCamelCase('test test') => 'testtest'. Please update solution with small fix. First RegExp should be /\s+(.)/g.Karajan
this fail if the str in UPPERCASEWalleye
S
402

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

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}

// all output "equipmentClassName"
console.log(camelize("EquipmentClass name"));
console.log(camelize("Equipment className"));
console.log(camelize("equipment class name"));
console.log(camelize("Equipment Class Name"));

Edit: Or in with a single replace call, capturing the white spaces also in the RegExp.

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\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();
  });
}
Sceptic answered 4/6, 2010 at 0:3 Comment(13)
Great code, and it ended up winning jsperf.com/js-camelcase/5 . Care to contribute a version that can handle (remove) non-alpha chars? camelize("Let's Do It!") === "let'SDoIt!" sad face. I'll try myself but fear I will just add another replace.Electrograph
.. since the non-alpha shouldn't affect the case, I'm not sure it can be done better than return this.replace(/[^a-z ]/ig, '').replace(/(?:^\w|[A-Z]|\b\w|\s+)/g,...Electrograph
Can you talk about the advantage of /(?:^\w|[A-Z]|\b\w)/ over /\b\w/? To me they look identical (although the second one is slightly simpler).Lundberg
For my ES2015+ friends: a one liner based on the above code. const toCamelCase = (str) => str.replace(/(?:^\w|[A-Z]|\b\w)/g, (ltr, idx) => idx === 0 ? ltr.toLowerCase() : ltr.toUpperCase()).replace(/\s+/g, '');Vendible
While this wasn't a case asked by example, another common input you'll likely see is "EQUIPMENT CLASS NAME", for which this method fails.Sheepherder
@EdmundReed you can simply convert the whole string to lowercase prior to converting to camel case by chaining the .toLowerCase() method in. Eg. using @tabrindle's solution above: const toCamelCase = (str) => str.toLowerCase().replace(/(?:^\w|[A-Z]|\b\w)/g, (ltr, idx) => idx === 0 ? ltr.toLowerCase() : ltr.toUpperCase()).replace(/\s+/g, '');Eugeniaeugenics
Will this work with _ MARK_BTNS_NEW, this string is not converted to camel caseFluttery
For undescore with upper case added str=str.toLowerCase().replace(/_/g, ' ');Fluttery
Not sure why str.replace(/(\b\w)/g) is not good enough. toUpperCase() should be a no-op on a non alpha character anyway.Azarria
@KeithTyler This always converts the first charater to uppercaseIncumbent
NOTE: i needed to convert snake_case strings (from DB columns), but this doesn't seem to workHadleigh
works not nice with umlauts and abbreviation. E. g.: camelize("ETA mit Männer") => "eTAMitMäNner"Karajan
@Eugeniaeugenics works for stuff like ID, for which this answer doesn't work, but it doesn't help for TitanCase like in the question, it would make it titancaseIntuitive
J
199

If anyone is using lodash, there is a _.camelCase() function.

_.camelCase('Foo Bar');
// → 'fooBar'

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

_.camelCase('__FOO_BAR__');
// → 'fooBar'
Jenelljenelle answered 5/5, 2016 at 2:15 Comment(2)
Why should one install a whole lodash package just for this purpose and the OP specifically wanted a solution using javascript regex.Pallor
@PeterMoses 1) My answer reads "If anyone is using lodash", not "you should install Lodash to do this" 2) Whilst the question body refers to JavaScript RegEx, many people land here because the title reads "Converting any string into camel case" 3) You do not need to import the "whole" lodash library; you can import just the methods you need, or use per method packages like lodash.camelcase instead (which has since been deprecated) 4) You can mitigate a large bundle by implementing tree shakingJenelljenelle
S
103

To get camelCase

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

To get camelCase or PascalCase

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

Note :
For those language with accents. Do include À-ÖØ-öø-ÿ with the regex as following
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g This is only for one language. For another language, you have to search and find

Sandhog answered 28/9, 2018 at 9:5 Comment(9)
ES6 just made everything lowercase for meBatholomew
@Luis added https://stackoverflow.com/posts/52551910/revisions ES6, I haven't tested it. I will check and update.Sandhog
Does not work for words with accents jsbin.com/zayafedubo/edit?js,consoleTopographer
@ManuelOrtiz - jsbin.com/cibimatove/2/edit?js,console I have edited. Please check. Also please don't mind if it was a meaningful word. I don't know the language with those accents. The code is .replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/gSandhog
it will not work if you pass camelized string. We need to check if we have already camalized string.Bessbessarabia
@SheikhAbdulWahid - I haven't tested your case though. But that is a different case and which need a condition !. A function with camalize will camalize it. That's all. But of course, we can think of adding a new condition in between.Sandhog
It doesn't work right when the string opens with a space: ` one two` -> OneTwo, should be oneTwo. Works properly in my answer ;)Constrained
you can try adding a space in the regex like how I added the other language script [^a-zA-Z0-9 ]Sandhog
Why use var in ES6 also this doesnt work for TitanCaseIntuitive
E
72

I just ended up doing 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 was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.

Ellerey answered 3/6, 2010 at 23:46 Comment(8)
That looks fine to me, and nothing looks suspicious as far as cross-browser issues. (Not that I'm a super-expert or anything.)Rectangular
If you're going to use the String.prototype, why not just use 'this' instead of sending a 'str' parameter?Flautist
Doesn't works in Safari. > "very active".toCamelCase() < TypeError: undefined is not an object (evaluating 'str .replace')Filiform
For better browser compatibility please use this instead of str (and remove the parameter from the function call)Filiform
You just need to use this.valueOf() instead of passing str. Alternatively (as in my case) this.toLowerCase() as my input strings were in ALL CAPS which didn't have the non-hump portions lowercased properly. Using just this returns the string object itself, which is actually an array of char, hence the TypeError mentioned above.Sickly
This returns the exact opposite of what's needed. This'll return sTRING.Gynaecology
Scott Klarenbach, Thank you for good solution. It just doesn't work if there are 2 whitespaces between words: toCamelCase('test test') => 'testtest'. Please update solution with small fix. First RegExp should be /\s+(.)/g.Karajan
this fail if the str in UPPERCASEWalleye
V
54

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('');
}
Verney answered 13/3, 2016 at 22:41 Comment(7)
This is uppercase, not camel.Roturier
Camel case is the first character of every word in a capital case, and toCamelCase function just does that.Verney
You are thinking of PascalCase. CamelCase can be either upper or lower case. In this context, it is often lower case to avoid confusion.Halicarnassus
@Halicarnassus is correct, you are confusing the definitions of camelCase and PascalCase.Suttles
Thanks @Halicarnassus ,@Suttles for your constructive comment, checkout the updated version.Verney
+1 for not use regular expressions, even if the question asked for a solution using them. This is a much clearer solution, and also a clear win for performance (because processing complex regular expressions is a much harder task than just iterating over a bunch of strings and joining bits of them together). See jsperf.com/camel-casing-regexp-or-character-manipulation/1 where I've taken some of the examples here along with this one (and also my own modest improvement of it for performance, although I would probably prefer this version for clarity's sake in most cases).Binnie
the .join('') at the end needs a space in there. Otherwise its a nice solutionRopy
C
38

Reliable, high-performance example:

function camelize(text) {
    const a = text.toLowerCase()
        .replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    return a.substring(0, 1).toLowerCase() + a.substring(1);
}

Case-changing characters:

  • hyphen -
  • underscore _
  • period .
  • space
Constrained answered 13/9, 2019 at 17:7 Comment(5)
For people who startout with an UPPERCASED string, first use: text = text.toLowerCase();Involutional
.substr is deprecated, use .substring now instead.Pastoralize
Both of the above comments are no longer applicable (The author).Constrained
when a string is already in camelcase, for example: "cApple", this returns a complete lowercase string "capple", can we prevent this?Freeswimming
@MiguelStevens Prevent what exactly? The conversion is correct. You can remove use of toLowerCase, but the whole method is not meant to be used repeatedly.Constrained
S
37

In Scott’s specific case I’d go with something like:

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

The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.

By spicing up the regex to /^([A-Z])|[\s-_](\w)/g it will also camelize hyphen and underscore type names.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
Subrogate answered 5/4, 2013 at 8:54 Comment(2)
what if there are more than 2,3 hypens or underscores in the string like .data-product-name,.data-product-description,.product-container__actions--price,.photo-placeholder__photoRutaceous
@AshwaniShukla In order to handle multiple hyphens and/or underscores you will have to add a multiplier (+) to the character group, i.e.: /^([A-Z])|[\s-_]+(\w)/gSubrogate
J
22
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 was trying to find a JavaScript function to camelCase a string, and wanted to make sure special characters would be removed (and I had trouble understanding what some of the answers above were doing). This is based on c c young's answer, with added comments and the removal of $peci&l characters.

Jarib answered 16/9, 2015 at 9:2 Comment(0)
B
13

If regexp isn't required, you might want to look at 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 haven't made any performance tests, and regexp versions might or might not be faster.

Balsaminaceous answered 4/6, 2010 at 0:29 Comment(1)
5x times faster on average, if you only need 1 word jsbin.com/wuvagenoka/edit?html,js,outputFerdelance
S
9

This function by pass cammelcase such these tests

  • Foo Bar
  • --foo-bar--
  • __FOO_BAR__-
  • foo123Bar
  • foo_Bar

function toCamelCase(str)
{
  var arr= str.match(/[a-z]+|\d+/gi);
  return arr.map((m,i)=>{
    let low = m.toLowerCase();
    if (i!=0){
      low = low.split('').map((s,k)=>k==0?s.toUpperCase():s).join``
    }
    return low;
  }).join``;
}
console.log(toCamelCase('Foo      Bar'));
console.log(toCamelCase('--foo-bar--'));
console.log(toCamelCase('__FOO_BAR__-'));
console.log(toCamelCase('foo123Bar'));
console.log(toCamelCase('foo_Bar'));

console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase('Equipment Class Name'));
Subgenus answered 7/1, 2021 at 11:51 Comment(1)
Algorithm-based camel-case transformation is a huge overkill and a performance hog.Constrained
B
9

To effectively create a function that converts the casing of a string to camel-case, the function will also need to convert each string to lower-case first, before transforming the casing of the first character of non-first strings to an uppercase letter.

My example string is:

"text That I WaNt to make cAMEL case"

Many other solutions provided to this question return this:

"textThatIWaNtToMakeCAMELCase"

What I believe would be the desired output would be this, though, where all the mid-string uppercase characters are first transformed to be lowercase:

"textThatIWantToMakeCamelCase"

This can be done WITHOUT using any replace() method calls, by utilizing the String.prototype.split(), Array.prototype.map(), and Array.prototype.join() methods:

≤ ES5 Version

function makeCamelCase(str) {
  return str
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

I'll break down what each line does, and then provide the same solution in two other formats— ES6 and as a String.prototype method, though I'd advise against extending built-in JavaScript prototypes directly like this.

Explainer

function makeCamelCase(str) {
  return str
    // split string into array of different words by splitting at spaces
    .split(' ')
    // map array of words into two different cases, one for the first word (`i == false`) and one for all other words in the array (where `i == true`). `i` is a parameter that denotes the current index of the array item being evaluated. Because indexes start at `0` and `0` is a "falsy" value, we can use the false/else case of this ternary expression to match the first string where `i === 0`.
    .map((e,i) => i
      // for all non-first words, use a capitalized form of the first character + the lowercase version of the rest of the word (excluding the first character using the slice() method)
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      // for the first word, we convert the entire word to lowercase
      : e.toLowerCase()
    )
    // finally, we join the different strings back together into a single string without spaces, our camel-cased string
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

Condensed ES6+ (One-Liner) Version

const makeCamelCase = str => str.split(' ').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join('')

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

String.prototype method version

String.prototype.toCamelCase = function() {
  return this
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

"text That I WaNt to make cAMEL case".toCamelCase()
// -> "textThatIWantToMakeCamelCase" ✅
Bonita answered 10/3, 2022 at 15:29 Comment(1)
LOL you can't call it a one liner just because you can possibly smash it all on a single line! But this is an elegant solution. It should be improved to remove any - or _ characters from the string as well, not just ' ' char.Aramenta
D
8

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"
Dorison answered 2/8, 2017 at 12:45 Comment(1)
what about names like Jean-Pierre ?Borneol
B
8

Here is a one liner doing the work:

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

It splits the lower-cased string based on the list of characters provided in the RegExp [.\-_\s] (add more inside the []!) and returns a word array . Then, it reduces the array of strings to one concatenated string of words with uppercased first letters. Because the reduce has no initial value, it will start uppercasing first letters starting with the second word.

If you want PascalCase, just add an initial empty string ,'') to the reduce method.

Buzz answered 18/6, 2018 at 10:19 Comment(0)
R
7

The top answer is terse but it doesn't handle all edge cases. For anyone needing a more robust utility, without any external dependencies:

function camelCase(str) {
    return (str.slice(0, 1).toLowerCase() + str.slice(1))
      .replace(/([-_ ]){1,}/g, ' ')
      .split(/[-_ ]/)
      .reduce((cur, acc) => {
        return cur + acc[0].toUpperCase() + acc.substring(1);
      });
}

function sepCase(str, sep = '-') {
    return str
      .replace(/[A-Z]/g, (letter, index) => {
        const lcLet = letter.toLowerCase();
        return index ? sep + lcLet : lcLet;
      })
      .replace(/([-_ ]){1,}/g, sep)
}

// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar  Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))

// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));

// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));

Demo here: https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark

Rhizobium answered 18/7, 2020 at 14:13 Comment(2)
What about the first character?Redivivus
@Redivivus I don't understand.Rhizobium
M
6

lodash can do the trick sure and well:

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

Although lodash may be a "big" library (~4kB), it contains a lot of functions that you'd normally use a snippet for, or build yourself.

Mckenna answered 29/7, 2016 at 13:37 Comment(1)
there are npm modules with each individual lodashfunction, so you don't need to import all the"big" library: npmjs.com/package/lodash.camelcaseSuburb
G
5
return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
    return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld
Generalize answered 7/3, 2017 at 10:33 Comment(0)
E
5

Because this question needed yet another answer...

I tried several of the previous solutions, and all of them had one flaw or another. Some didn't remove punctuation; some didn't handle cases with numbers; some didn't handle multiple punctuations in a row.

None of them handled a string like a1 2b. There's no explicitly defined convention for this case, but some other stackoverflow questions suggested separating the numbers with an underscore.

I doubt this is the most performant answer (three regex passes through the string, rather than one or two), but it passes all the tests I can think of. To be honest, though, I really can't imagine a case where you're doing so many camel-case conversions that performance would matter.

(I added this as an npm package. It also includes an optional boolean parameter to return Pascal Case instead of 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('A B 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`);
});
Evacuee answered 11/10, 2018 at 3:7 Comment(0)
S
4

following @Scott's readable approach, a little bit of fine tuning

// 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, '' );
}
Streusel answered 2/11, 2012 at 2:32 Comment(1)
Camel transformation can be easily done with 1 replace, not 4.Constrained
M
3

little modified Scott's answer:

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

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

Mascle answered 27/7, 2015 at 13:10 Comment(0)
V
3

All 14 permutations below produce the same result of "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());
};
Velda answered 14/9, 2015 at 11:4 Comment(1)
Yeah. I like the use of prototype methods with strings rather than functions. It helps with chaining.E
D
3

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());
Domitian answered 14/5, 2016 at 9:3 Comment(1)
This example show you how to use two another function in replace method.Domitian
A
3

Here's 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');
  });
});
Assoil answered 28/12, 2018 at 1:46 Comment(0)
C
2

This method seems to outperform most answers on here, it's a little bit hacky though, no replaces, no regex, simply building up a new string that's 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;
}
Cathode answered 21/1, 2016 at 11:1 Comment(0)
D
2

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'))
Deutsch answered 22/5, 2018 at 11:54 Comment(0)
T
1

This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w does not remove.

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\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
Tartary answered 18/3, 2016 at 9:39 Comment(0)
T
1

Upper camel case ("TestString") to lower camel case ("testString") without using regex (let's face it, regex is evil):

'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');
Tameika answered 10/5, 2017 at 9:54 Comment(1)
Single character parameters are still slightly evil in terms of readabilityPossessed
K
1

I ended up crafting 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 uppercased, e.g.

  • Size (comparative) => sizeComparative
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello
Keller answered 11/7, 2017 at 8:59 Comment(0)
P
1
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('');
}      
Previdi answered 17/10, 2017 at 18:14 Comment(0)
H
1

I know this is an old answer, but this handles both whitespace and _ (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"
Hadleigh answered 16/7, 2019 at 15:11 Comment(1)
Thanks for this, but there appears to be a stray " in .replace(/_/g", " ") that causes compilation errors?Stabler
F
1
const toCamelCase = str =>
  str
    .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
    .replace(/^\w/, c => c.toLowerCase());
Fireeater answered 3/12, 2019 at 19:23 Comment(0)
N
1

Most answers do not handle unicode characters, e.g. accented characters.

If you want to handle unicode and accents, the following works in any modern browser:

camelCase = s => s
   .replace( /(?<!\p{L})\p{L}|\s+/gu,
              m => +m === 0 ? "" : m.toUpperCase() )
   .replace( /^./, 
             m => m?.toLowerCase() );

A couple of explanations:

  1. because the question requires that the first character be lowercase, the second replace call is necessary.
  2. the first replace call identifies any unicode letter that follows any non letter (equivalent of \b\w but working for non ASCII letters). The u flag (unicode) is necessary for this to work.

Note that this will keep uppercase letters unchanged. This is useful if your input text contains acronyms.

e.g.

console.log(camelCase("Shakespeare in FR is être ou ne pas être");
// => 'ShakespeareInFRIsÊtreOuNePasÊtre'

If you want pure camelCase where acronyms are turned lowercase, you can lower case the input text first.

Nicolina answered 23/4, 2022 at 11:4 Comment(0)
S
1

Coderbyte Camel Case Solution

Problem:

Have the function CamelCase(str) take the str parameter being passed and return it in proper camel case format where the first letter of each word is capitalized (excluding the first letter). The string will only contain letters and some combination of delimiter punctuation characters separating each word.

For example: if str is "BOB loves-coding" then your program should return the string bobLovesCoding.

Solution:

function CamelCase(str) {
  return str
    .toLowerCase()
    .replace(/[^\w]+(.)/g, (ltr) => ltr.toUpperCase())
    .replace(/[^a-zA-Z]/g, '');
}
// keep this function call here 
console.log(CamelCase("cats AND*Dogs-are Awesome"));
console.log(CamelCase("a b c d-e-f%g"));
Schramm answered 30/7, 2022 at 3:42 Comment(0)
R
0

Basic approach would be to split the string with a regex matching upper-case or spaces. Then you'd glue the pieces back together. Trick will be dealing with the various ways regex splits are broken/weird across browsers. There's a library or something that somebody wrote to fix those problems; I'll look for it.

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

Rectangular answered 3/6, 2010 at 23:34 Comment(0)
Q
0

EDIT: Now working in IE8 without changes.

EDIT: I was in the minority about what camelCase actually is (Leading character lowercase vs. uppercase.). The community at large believes a leading lowercase is camel case and a leading capital is pascal case. I have created two functions that use regex patterns only. :) So we use a unified vocabulary I have changed my stance to match the majority.


All I believe you need is a single regex in either case:

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 replace is swapping any non a-z with a space vs an empty string. This is 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 vs adding the case insensitivity flag (i) to the pattern (/[^A-Z]/ig) for readability.
  • This works in IE8 (srsly, who uses IE8 anymore.) Using the (F12) dev tools I have tested in IE11, IE10, IE9, IE8, IE7 and IE5. Works in all document modes.
  • This will correctly case the first letter of strings starting with or without whitespace.

Enjoy

Quemoy answered 18/12, 2016 at 19:44 Comment(6)
The first letter is still capitalized?Ottava
Yes. It will be capitalized in the case it is lower or upper to start.Quemoy
Well that's not camel case - and doesn't match what the OP requested?Ottava
Well hopefully this edit provides the results the OP was looking for. For the life of me I had no idea what the downvote was for. Not answering the OP ... That will do it. :)Quemoy
I believe "PascalCase" is what we call camelCase with a leading capital.Gramps
I hope this is now in line with the community opine overall.Quemoy
A
0

Don't use String.prototype.toCamelCase() because String.prototypes are read-only, most of the js compilers will give you this warning.

Like me, those who know that the string will always contains 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 good day. :)

Alsatia answered 21/1, 2019 at 4:41 Comment(0)
M
0

I came up with this one liner which also works with kebab-case to CamelCase:

string.replace(/^(.)|[\s-](.)/g,
                (match) =>
                    match[1] !== undefined
                        ? match[1].toUpperCase()
                        : match[0].toUpperCase()
            )
Methane answered 22/7, 2021 at 19:27 Comment(0)
W
0

This will convert any case string with spaces to thisWordsInCamelCase

function toCamelCase(str) {
  return str.toString() && str.split(' ').map((word, index) => {
    return (index === 0 ? word[0].toLowerCase() : word[0].toUpperCase()) + word.slice(1).toLowerCase()
  }).join('');
}
Walleye answered 26/2, 2022 at 3:35 Comment(1)
Whether or not the function works, as a general rule of thumb, you should not modify Javascript object prototypes. For reasons why, see here.Rigamarole
R
0

One funny way to do that is via dataset property.

function camelize(dashString) {
  let el = document.createElement('div')
  el.setAttribute('data-'+dashString,'')
  return Object.keys(el.dataset)[0]
}

console.log(camelize('x-element')) // 'xElement'
Refresh answered 21/4, 2022 at 21:46 Comment(0)
V
0

This solves it for me, dealing with special characters and prepositions

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(' ');
}
Vegetable answered 7/11, 2022 at 23:18 Comment(0)
C
0

Here is the solution, including the uppercasing of the first letter if the first letter was initially uppercase.

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


Corneliuscornell answered 18/11, 2022 at 6:5 Comment(0)
A
-1

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('');
}
Ama answered 17/8, 2018 at 6:17 Comment(0)
A
-1

A 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 case variations.

More info here:

Convert string to CamelCase, UpperCamelCase or lowerCamelCase

Adventuresome answered 4/11, 2018 at 9:29 Comment(3)
A whole library for a one-liner implementation - that's crazy.Constrained
If you are not lazy, go to the library github page and see the code for this implementation. And also, you will get tons of common "one-liner" implementations for free, which will help you in your daily development tasks.Adventuresome
Don't call me lazy. I published a one-liner solution to the question, without trying to take people away to some unknown library you are advertising here.Constrained
A
-1

simple & easy to understand this code hope this will helpful to you i fixed my problem using below logic

// This example is for React Js User

const ConverToCamelCaseString = (StringValues)=> 
{
    let WordsArray = StringValues.split(" ");
    let CamelCaseValue = '';
    for (let index = 0; index < WordsArray.length; index++) 
    {
        let singleWord = WordsArray[index];
            singleWord.charAt(0).toUpperCase();
            singleWord =singleWord.charAt(0).toUpperCase() + singleWord.slice(1);

        CamelCaseValue +=" "+singleWord;
        
    }
    CamelCaseValue = CamelCaseValue.trim();
    return CamelCaseValue;
}

This below example is for core javaScript Users

function ConverToCamelCaseString (StringValues) 
    {
        let WordsArray = StringValues.split(" ");
        let CamelCaseValue = '';
        for (let index = 0; index < WordsArray.length; index++) 
        {
            let singleWord = WordsArray[index];
                singleWord.charAt(0).toUpperCase();
                singleWord =singleWord.charAt(0).toUpperCase() + singleWord.slice(1);

            CamelCaseValue +=" "+singleWord;
            
        }
        CamelCaseValue = CamelCaseValue.trim();
        return CamelCaseValue;
    }

console.log(ConverToCamelCaseString("this is my lower case string")); 

I hope above examples will solve your problem Happy Coding.!

Ainu answered 16/10, 2022 at 10:30 Comment(0)
C
-1
var cadena = "mOnIcA";
console.log(cadena.substr(0,1).toUpperCase()+(cadena.substr(1,[cadena.length]).toLowerCase()));
Cush answered 2/10, 2023 at 19:42 Comment(2)
Please [edit[ this post to contain an explanation on why this works. Always remember you're not only answering the question, but are also educating the OP and future readers, see How to Answer.Outset
This does not work. Please see the test cases in the question.Agglomeration
G
-2

Quick way

function toCamelCase(str) {
    return str[0].toUpperCase() + str.substr(1).toLowerCase();
}
Gausman answered 2/12, 2021 at 19:11 Comment(1)
Not camelCase. Doesn't handle spaces.Jalbert

© 2022 - 2024 — McMap. All rights reserved.