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

后端 未结 11 913
北荒
北荒 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:09

    This can be concisely done with regex lookahead (live demo):

    function splitCamelCaseToString(s) {
        return s.split(/(?=[A-Z])/).join(' ');
    }
    

    (I thought that the g (global) flag was necessary, but oddly enough, it isn't in this particular case.)

    Using lookahead with split ensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:

    function splitCamelCaseToString(s) {
        return s.split(/(?=[A-Z])/).map(function(p) {
            return p.charAt(0).toUpperCase() + p.slice(1);
        }).join(' ');
    }
    

    The map array method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a for loop.

提交回复
热议问题