Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
To convert string to camel case in javascript.
function toCamelCase(str) {
return str.toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
return match.charAt(match.length-1).toUpperCase();
});
}
@mastershashi

This comment has been minimized.

Copy link

@mastershashi mastershashi commented Mar 13, 2018

Hi Johnsmith,

I need to put space between string Eg: Current String "HelloWorld" , I need "Hello World"
could you please help me in this ?

Regards,
Shashi

@assembledadam

This comment has been minimized.

Copy link

@assembledadam assembledadam commented Mar 14, 2018

Note this JS doesn't appear to work (at least not to covert snake or kebab case to camel case. Appears to want to convert a space delimited string.

For those wanting snake case to camel case, go here: https://gist.github.com/assembledadam/80c97eb03fdc35e1e92ae38537a02ac0

@mcarlucci

This comment has been minimized.

Copy link

@mcarlucci mcarlucci commented Apr 23, 2018

This is Pascal Case (PascalCase), not Camel Case (camelCase). In other words, camel case is when the first letter is lower case.

@timhobbs

This comment has been minimized.

Copy link

@timhobbs timhobbs commented Jun 6, 2018

function toCamelCase(string) {
    string = string.toLowerCase().replace(/(?:(^.)|([-_\s]+.))/g, function(match) {
        return match.charAt(match.length-1).toUpperCase();
    });
    return string.charAt(0).toLowerCase() + string.substring(1);
}

Small changes to the above to allow for kebab and snake case input, as well as proper camelCase rather than PascalCase as @mcarlucci pointed out.

Fork: https://gist.github.com/timhobbs/23c891bfea312cf43f31395d2d6660b1

EDIT: I tried the gist from @assembledadam above but it did not seem to work for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.