我使用类似这样的函数,它接受一个可选的第二个参数,该参数将首先将整个字符串转换为小写字母。原因是有时你有一系列Title Case Items. That You Wish
变成一系列Title case items. That you wish
作为判例。
function sentenceCase(input, lowercaseBefore) {
input = (input === undefined || input === null) ? '' : input;
if (lowercaseBefore) { input = input.toLowerCase(); }
return input.toString().replace(/(^|\. *)([a-z])/g, function(match, separator, char) {
return separator + char.toUpperCase();
});
}
正则表达式的工作原理如下
1st Capturing Group (^|\. *)
1st Alternative^
^asserts position at start of the string
2nd Alternative \. *
\. matches the character `.` literally (case sensitive)
* matches the character ` ` literally (case sensitive)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([a-z])
Match a single character present in the list below [a-z]
a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)
你会实现它在你的榜样,像这样:
var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!
例jsfiddle
PS。在未来,我觉得regex101了解和测试正则表达式的
的可能的复制[字符串转换为一句JavaScript的情况下(http://stackoverflow.com/questions/19089442/convert-string-to-sentence-case-in-javascript) – Fiddles
也请参阅http: //stackoverflow.com/q/37457557/405180 – Fiddles