且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JavaScript中将驼峰大小写转换为句子大小写

更新时间:2021-11-07 04:32:38

以下使用首字母大写的缩写形式;我不同意Microsoft的建议,即使用两个以上字符时要大写,因此,即使在字符串的开头,也希望整个首字母都大写(从技术上讲,这不是驼峰大小写,但它提供了可控制的合理输出),多个连续的首字母缩写可以使用 _ 进行转义(例如 parseDBM_MXL -> Parse DBM XML ).

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));
});