简体   繁体   English

在 javascript 中将骆驼案例转换为句子案例

[英]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:我发现自己需要在支持首字母缩略词的情况下将驼峰式大小写转换为句子大小写字符串,谷歌搜索想法让我找到了以下 SO 帖子:

Convert camelCaseText to Sentence Case Text 将 camelCaseText 转换为句子大小写文本

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.这实际上是在询问标题大小写而不是句子大小写,所以我想出了以下解决方案,也许其他人会觉得有帮助或可以提供改进,它使用的是我可以接受的 ES6,如果有一些可怕的IE要求,可以很容易地填充.

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 _ (eg parseDBM_MXL -> Parse DBM XML ).我不同意微软关于在超过两个字符时大写的建议,因此即使它位于字符串的开头,这也期望整个首字母大写(这在技术上意味着它不是驼峰式,但它提供了理智的可控输出),多个连续的首字母缩略词可以用_转义(例如parseDBM_MXL -> Parse DBM XML )。

 function camelToSentenceCase(str) { return str.split(/([AZ]|\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)); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM