Convert Camel Case To Sentence Case In Javascript
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 camelCaseTe
Solution 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
).
functioncamelToSentenceCase(str) {
return str.split(/([A-Z]|\d)/).map((v, i, arr) => {
// If first block then capitalise 1st letter regardlessif (!i) return v.charAt(0).toUpperCase() + v.slice(1);
// Skip empty blocksif (!v) return v;
// Underscore substitutionif (v === '_') return" ";
// We have a capital or numberif (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 spaceif (!previousCapital || nextWord) v = " " + v;
// Start of word or single letter wordif (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));
});
Post a Comment for "Convert Camel Case To Sentence Case In Javascript"