Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 939
user1048007 Avatar asked Jan 21 '12 18:01

user1048007


4 Answers

Try something like:

var myStr = 'thisString';

myStr = myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
like image 174
Wouter J Avatar answered Nov 07 '22 15:11

Wouter J


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
like image 20
Syon Avatar answered Nov 07 '22 16:11

Syon


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

like image 5
Alex Avatar answered Nov 07 '22 15:11

Alex


String.prototype.camelCaseToDashed = function(){
  return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// Usage
"SomeVariable".camelCaseToDashed();
like image 1
Bilal Iqbal Avatar answered Nov 07 '22 15:11

Bilal Iqbal