zso*_*457 5 javascript regex string lowercase capitalization
我有一个字符串
FIRST SENTENCE. SECOND SENTENCE.
我想以这种方式小写字符串以大写每个句子的第一个字母.
例如:
string = string.toLowerCase().capitalize();
Run Code Online (Sandbox Code Playgroud)
只有第一句是大写的.
我有
String.prototype.capitalize = function(){return this.charAt(0).toUpperCase()+ this.slice(1); }
功能
有谁知道如何解决?
squ*_*age 10
如果你只想把每个句子的第一个单词(不是每个单词)都大写,那么使用这个函数:
function applySentenceCase(str) {
return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
Run Code Online (Sandbox Code Playgroud)
如果您想保留句子其余部分的格式并只是将首字母大写,请更改txt.substr(1).toLowerCase()为txt.substr(1)