Convert camel case to sentence case in javascript

寵の児 提交于 2021-02-11 12:18:57

问题


I found myself needing to do camel case to sentence case string conversion with sane acronym support, a google search for ideas led me to the following SO post:

Convert camelCaseText to Sentence Case Text

Which is actually asking about title case not sentence case so I came up with the following solution which maybe others will find helpful or can offer improvements to, it is using ES6 which is acceptable for me and can easily be polyfilled if there's some horrible IE requirement.


回答1:


The below uses capitalised notation for acronyms; I don't agree with Microsoft's recommendation of capitalising when more than two characters so this expects the whole acronym to be capitalised even if it's at the start of the string (which technically means it's not camel case but it gives sane controllable output), multiple consecutive acronyms can be escaped with _ (e.g. parseDBM_MXL -> Parse DBM XML).

function camelToSentenceCase(str) {
    return str.split(/([A-Z]|\d)/).map((v, i, arr) => {
        // If first block then capitalise 1st letter regardless
        if (!i) return v.charAt(0).toUpperCase() + v.slice(1);
        // Skip empty blocks
        if (!v) return v;
        // Underscore substitution
        if (v === '_') return " ";
        // We have a capital or number
        if (v.length === 1 && v === v.toUpperCase()) {
            const previousCapital = !arr[i-1] || arr[i-1] === '_';
            const nextWord = i+1 < arr.length && arr[i+1] && arr[i+1] !== '_';
            const nextTwoCapitalsOrEndOfString = i+3 > arr.length || !arr[i+1] && !arr[i+3];
            // Insert space
            if (!previousCapital || nextWord) v = " " + v;
            // Start of word or single letter word
            if (nextWord || (!previousCapital && !nextTwoCapitalsOrEndOfString)) v = v.toLowerCase();
        }
        return v;
    }).join("");
}


// ----------------------------------------------------- //

var testSet = [
    'camelCase',
    'camelTOPCase',
    'aP2PConnection',
    'JSONIsGreat',
    'ThisIsALoadOfJSON',
    'parseDBM_XML',
    'superSimpleExample',
    'aGoodIPAddress'
];

testSet.forEach(function(item) {
    console.log(item, '->', camelToSentenceCase(item));
});


来源:https://stackoverflow.com/questions/65705297/convert-camel-case-to-sentence-case-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!