有没有办法忽略标题大小写方法中的首字母缩略词?



Background

我有一个要转换为标题大小写的电视节目列表。我目前的代码在"bojack Horseman","Family GUY"和"jessica jones"等程序上运行良好。但是,我的一些程序中包含首字母缩略词。因此,像"paradise pd"这样的标题将被转换为"Paradise Pd"。

我已经研究了正则表达式作为一种可能的解决方案,并访问了一些网站,特别是(Regex101([https://regex101.com/],看看我是否能找到一些东西。也许我没有在他们的图书馆中使用正确的搜索词,但我在那里没有运气。

这是我想做的事情的最佳解决方案还是有更好的方法?

我的代码现状

titleSort = () => {
// make sure all program names are in title case
let titleCasePrograms = this.props.programs.map(program => program.name.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' '))
}

我希望完成什么

上面的代码是我正在编写的用于按字母顺序对名称进行排序的较大批次的一部分。但是,在我开始实际的排序方法之前,我想确保我考虑了我将遇到的不同类型的单词并正确格式化它们。:-)

非常感谢您的时间和建议!

计算机无法知道首字母缩略词是什么,因此您需要有一个首字母缩略词列表。完成此操作后,只需将该列表的检查添加到转换中即可。像这样:

const acronyms = ['PD', 'MD', 'ASAP', 'NCIS']; // ...etc....
titleSort = () => {
let titleCasePrograms = this.props.programs.map(program => {
return program.name.split(' ')
.map(w => {
if (acronyms.includes(w.toUpperCase())) {
return w.toUpperCase();
}
return w[0].toUpperCase() + w.substr(1).toLowerCase();
})
.join(' ')
);
}

超级晚了,但我遇到了类似的问题并以这种方式处理它。在我的情况下,我为首字母缩略词设置的定义是任何带有两个大写字母的单词。

这意味着它将处理"ABC","A.B.C.","AOFBOFC"。它有一些边缘处理,但你可能仍然需要注意你的拼写。这很简单,但无论如何,我希望它能帮助某人。

const str = "Lorem ABC Dolor Sit Amet, RCMP Adipiscing Elit, TBS Do Eiusmod Tempor R.C.M.P. Ut Labore Et IO Magna Aliqua.";
//Helper function, sentence case strings, excluding acronyms
function toSentenceCase (str) {

//Helper function to manage a single sentence
function caseHandler(str){
let arr = str.split(' ');

//Test each word to see if an acronym
return arr.map(function(item, i){
//If not the first word
if(i > 0 ){
//Test with regex for acronym, if true, leave alone
if(/[A-Z].*[A-Z]+.*/.test(item)){
return item;
}
//If not an acronym, titlecase the word
else {
return item.charAt(0).toUpperCase() + item.slice(1);
} 
}
//If the first word, titlecase the word
else {
return item.charAt(0).toUpperCase() + item.slice(1);
}
}).join(' ')
}
//Splits strings by sentence
const stringsArr = str.split('. ')
//Temp arr
let sentenceArr = [];
//Loop through sentences
stringsArr.forEach(function(item) {
//For each sentence, call our caseHandler, push result to temp arr
sentenceArr.push(caseHandler(item))
})
//Join the array the same way that we split the string
return sentenceArr.join('. ')
}
const name = document.querySelector("#app");
name.textContent = toSentenceCase(str);
<div id="app"></div>

相关内容

最新更新