Convert dash-separated string to camelCase?

后端 未结 13 1163
爱一瞬间的悲伤
爱一瞬间的悲伤 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:41

    This should also work:

    function camelCase(str) {
      return str.replace(/^.|-./g, function(letter, index) {
        return index == 0 ? letter.toLowerCase() : letter.substr(1).toUpperCase();
      });
    }
    

    And IMHO it is little bit more efficient since we're not converting whole input string to lowercase first and then convert to uppercase if needed. This function only converts first letter to lowercase and then every character after hyphen - to uppercase.

提交回复
热议问题