2016-11-18 60 views
1

如何在字符串開頭和點(。)符號之後大寫每個單詞?在每個點(。)和字符串開始後大寫單詞

我做了谷歌計算器研究,以下是我實現但這隻會利用字符串的開始的代碼。示例如下:

var str = 'this is a text. hello world!'; 
 
str = str.replace(/^(.)/g, str[0].toUpperCase()); 
 
document.write(str);

我希望字符串是This is a text. Hello world!.

我曾嘗試使用CSS,text-transform: capitalize;但是這將導致每個字被利用。

+0

的可能的複製[字符串轉換爲一句JavaScript的情況下(http://stackoverflow.com/questions/19089442/convert-string-to-sentence-case-in-javascript) – Fiddles

+0

也請參閱http: //stackoverflow.com/q/37457557/405180 – Fiddles

回答

2

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

+0

謝謝@haxxxton。它的工作很棒! – Amran

+0

@Amran,不客氣,請考慮將此答案標爲正確,以便其他人可以找到此解決方案 – haxxxton

+0

替換函數如何工作?對不起,但我很困惑 – Amran

1

如果您正在使用jQuery,使用此代碼

function capitalize(str) { 
    return str.charAt(0).toUpperCase() + str.slice(1); 
} 
var str = "my name is Jhon. are you good. is it"; 
var str1 = str.split('.'); 
var str2 = ""; 
$.each(str1,function(i){ 
    str2 += capitalize($.trim(str1[i]))+'. '; 
}); 
console.log(str2); 

漁獲出來放在str2一個非常有用的工具。 在我的情況如下。

My name is Jhon. Are you good. Is it. 
+0

我可以知道我在函數(i) – Amran

+0

中我是什麼,我是循環的索引,從0開始到數組長度 –

+0

Ic,在你的例子中它會停在索引1上。我是否正確? – Amran

相關問題