Convert dash-separated string to camelCase?

后端 未结 13 1259
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 11:01

For example suppose I always have a string that is delimited by \"-\". Is there a way to transform

it-is-a-great-day-today

to

itIsAGreatDayToday

13条回答
  •  情话喂你
    2020-12-24 11:52

    You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):

    function camelCase(s) {
      return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
        return m.toUpperCase().replace(/-/,'');
      });
    }
    camelCase('foo-bar'); // => 'FooBar'
    camelCase('FOo-BaR-gAH'); // => 'FooBarGah'
    

提交回复
热议问题