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

JavascriptRegexSplitCamelcasing

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Try something like:

var myStr = 'thisString';

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

Solution 2 - Javascript

Late to answer, but this solution will work for cases where a single letter is camel cased.

'thisIsATest'.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase();  // this-is-a-test

Solution 3 - Javascript

Try the following:

var token = document.getElementsByTagName('strong')[0].innerHTML,
    replaced = token.replace(/[a-z][A-Z]/g, function(str, offset) {
       return str[0] + '-' + str[1].toLowerCase();
    });

alert(replaced);

Example - http://jsfiddle.net/7DV6A/2/

Documentation for the string replace function:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

Solution 4 - Javascript

String.prototype.camelCaseToDashed = function(){
  return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// Usage
"SomeVariable".camelCaseToDashed();

Solution 5 - Javascript

I don't know why all these solutions are so complex but i simply found this to be enough:

function camelCaseToDash(input){ 
     // replace Capital letter with the letter + a dash: '-', then lowercase everything.
     return input.replace(/([A-Z])/g, '-$1').toLowerCase(); 
}    

//or, using a callback function, directly lowercasing.
function camelCaseToDashCallback(input){
     //replace capital letter with lowercase variant + a dash '-'.
     return input.replace(/([A-Z])/g, (x)=> "-"+ x.toLowerCase());
}    

generally option 1 is faster though: https://jsfiddle.net/4557z/17/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1048007View Question on Stackoverflow
Solution 1 - JavascriptWouter JView Answer on Stackoverflow
Solution 2 - JavascriptSyonView Answer on Stackoverflow
Solution 3 - JavascriptAlexView Answer on Stackoverflow
Solution 4 - JavascriptBilal IqbalView Answer on Stackoverflow
Solution 5 - JavascriptJoel HarkesView Answer on Stackoverflow