0

I'm trying to turn a string from PascalCase to param-case:

'HelloWorld'.replace(/([A-Z])/g, (str) => { return '-' + str.toLowerCase() })
"-hello-world"

As you can see, I'm almos there ... I just have to remove the - at the beginning of the string. How to do that?

SeinopSys
  • 8,787
  • 10
  • 62
  • 110
alex
  • 7,111
  • 15
  • 50
  • 77
  • Possible duplicate of [Remove first character from a Javascript string](http://stackoverflow.com/questions/3923015/remove-first-character-from-a-javascript-string) – SeinopSys Mar 25 '16 at 10:10

2 Answers2

3

In your Code, for removing the first word, you just need to ignore the first character by using substring(1) off your rest of the output

var output = 'HelloWorld'.replace(/([A-Z])/g, (str) => { return '-' + str.toLowerCase() }).substring(1);

or alternatively you can convert from pascalcase to camelcase by doing this

var output = 'HelloWorld'.split(/(?=[A-Z])/g).map(function(value){ return value.charAt(0).toLowerCase()+ value.substring(1)}).join("-");

DEMO Below

var output = 'HelloWorld'.split(/(?=[A-Z])/g).map(function(value){ return value.charAt(0).toLowerCase()+ value.substring(1)}).join("-");
document.body.innerHTML += output;
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

You can use follow code:

var name = "HelloWorld";
var paramCaseName = name.replace(/([A-Z]+(.))/g, function(_, separator, letter, offset) {
  return (offset ? "-" + separator : separator).toLowerCase();
});
console.log(paramCaseName);

Based on angular source code.

Stepan Kasyanenko
  • 3,176
  • 1
  • 15
  • 23