我正在尝试将每个句子的开头转换为upercase字符。到目前为止这是有效的。 但我还需要定义一些异常(缩写)。在这些缩写之后,下一个单词不应该转换为大写。
这是我尝试过的,但它不起作用:
const abbrevs = ['ign.'];
var regex = new RegExp('(?!' + abbrevs.join('|') + ').+?(?:[.?!]\s|$)', 'g');
string.replace(regex, function(s) { return s.charAt(0).toUpperCase() + s.slice(1); })
实施例
this ign. is an example. this should get capitalized
应该得到:
This ign. is an example. This should get capitalized
答案 0 :(得分:1)
你可以:
'ign.'
及其他所有缩写替换为'abbreviation<ign>'
或'some_keyword_probably_not_found_in_strings<ign>'
abbreviation<ign>
转换回ign.
。以下是一个例子:
const abbrevs = ['ign', 'abc'];
var string = "this ign. is an example. this abc. is another example. this should get capitalized.";
console.log(string);
abbrevs.forEach(function(abbrev) {
string = string.replace(new RegExp(abbrev+'\.', 'g'), 'abbreviation<'+abbrev+'>');
});
console.log(string);
function applySentenceCase(str) {
return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
string = applySentenceCase(string);
console.log(string);
string = string.replace(new RegExp('abbreviation<(.*?)>', 'g'), "$1.");
console.log(string);