How to convert “camelCase” to “Camel Case”?

后端 未结 11 970
北荒
北荒 2020-11-27 10:25

I’ve been trying to get a JavaScript regex command to turn something like \"thisString\" into \"This String\" but the closest I’ve gotten is replac

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 11:13

    I think this should be able to handle consecutive uppercase characters as well as simple camelCase.

    For example: someVariable => someVariable, but ABCCode != A B C Code.

    The below regex works on your example but also the common example of representing abbreviations in camcelCase.

    "somethingLikeThis"
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([a-z])/g, ' $1$2')
        .replace(/\ +/g, ' ') => "something Like This"
    
    "someVariableWithABCCode"
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([a-z])/g, ' $1$2')
        .replace(/\ +/g, ' ') => "some Variable With ABC Code"
    

    You could also adjust as above to capitalize the first character.

提交回复
热议问题