Javascript/jQuery: Split camelcase string and add hyphen rather than space

user1048007 picture user1048007 · Jan 21, 2012 · Viewed 18.6k times · Source

I would imagine this is a multiple part situation with regex, but how would you split a camelcase string at the capital letters turning them in to lowercase letters, and then adding a hyphen between each new string?

For example:

thisString

would become:

this-string

Answer

Wouter J picture Wouter J · Jan 21, 2012

Try something like:

var myStr = 'thisString';

myStr = myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();