我使用類似這樣的函數,它接受一個可選的第二個參數,該參數將首先將整個字符串轉換爲小寫字母。原因是有時你有一系列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