Convert dash-separated string to camelCase?

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

    Yes (edited to support non-lowercase input and Unicode):

    function camelCase(input) { 
        return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
            return group1.toUpperCase();
        });
    }
    

    See more about "replace callbacks" on MDN's "Specifying a function as a parameter" documentation.

    The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).

提交回复
热议问题