JavaScript String – toUpperCase() 方法
JavaScript中的Strings是一種可變的數(shù)據(jù)類型。愛掏網(wǎng) - it200.com也就是說,您可以對(duì)其進(jìn)行修改和轉(zhuǎn)換。愛掏網(wǎng) - it200.com其中,toUpperCase()方法就是一種轉(zhuǎn)換方法,可以把字符串中所有的小寫字母轉(zhuǎn)換為大寫字母。愛掏網(wǎng) - it200.com
toUpperCase()方法不需要任何參數(shù),語法如下:
string.toUpperCase()
其中,string
是需要轉(zhuǎn)換的字符串。愛掏網(wǎng) - it200.com該方法會(huì)返回一個(gè)新字符串,其中所有的小寫字母都被轉(zhuǎn)換成大寫字母。愛掏網(wǎng) - it200.com
toUpperCase() 方法示例
讓我們看一下如何使用toUpperCase()方法。愛掏網(wǎng) - it200.com
let str1 = "hello world";
let str2 = str1.toUpperCase();
console.log(str1); // "hello world"
console.log(str2); // "HELLO WORLD"
在上面的示例中,首先定義了一個(gè)字符串str1
,其中包含一些小寫字母。愛掏網(wǎng) - it200.com然后,我們通過調(diào)用toUpperCase()
方法將其轉(zhuǎn)換為一個(gè)新字符串str2
,其中所有的小寫字母都被轉(zhuǎn)換成大寫字母。愛掏網(wǎng) - it200.com最后,我們通過console.log()
函數(shù)輸出了兩個(gè)字符串的值。愛掏網(wǎng) - it200.com
我們還可以使用鏈?zhǔn)秸{(diào)用來對(duì)字符串進(jìn)行多次轉(zhuǎn)換。愛掏網(wǎng) - it200.com例如:
let str1 = "hello world";
let str2 = str1.toUpperCase().split(" ");
console.log(str2); // ["HELLO", "WORLD"]
在上面的示例中,首先將字符串str1
轉(zhuǎn)換為大寫字母,然后使用split()
方法將其劃分為一個(gè)字符串?dāng)?shù)組str2
,以空格作為分隔符。愛掏網(wǎng) - it200.com最后,我們通過console.log()
函數(shù)輸出了數(shù)組的值。愛掏網(wǎng) - it200.com
toUpperCase() 方法支持 Unicode
值得注意的是,toUpperCase()方法支持Unicode,并能正確的將非ASCII字符轉(zhuǎn)換為大寫字母。愛掏網(wǎng) - it200.com例如:
let str1 = "?sterreich";
let str2 = str1.toUpperCase();
console.log(str2); // "?STERREICH"
在上面的示例中,我們先定義了一個(gè)包含非ASCII字符的字符串str1
,然后通過調(diào)用toUpperCase()
方法將其轉(zhuǎn)換為str2
,其中包含正確的大寫字母。愛掏網(wǎng) - it200.com這是因?yàn)镴avaScript的字符串是支持Unicode的。愛掏網(wǎng) - it200.com
toUpperCase() 方法與 localeCompare() 方法
在進(jìn)行字符串比較時(shí),toUpperCase()方法常常與localeCompare()方法一起使用,以確保字符串的大小寫不影響結(jié)果。愛掏網(wǎng) - it200.com
例如:
let str1 = "banana";
let str2 = "BANANA";
console.log(str1.localeCompare(str2)); // 1
console.log(str1.toUpperCase().localeCompare(str2.toUpperCase())); // 0
在上面的示例中,我們首先定義了兩個(gè)不同大小寫的字符串str1
和str2
,然后使用localeCompare()
方法比較它們的值。愛掏網(wǎng) - it200.com由于這兩個(gè)字符串的大小寫是不同的,因此比較結(jié)果是1。愛掏網(wǎng) - it200.com然后,我們將兩個(gè)字符串都轉(zhuǎn)換為大寫字母,并再次使用localeCompare()
方法進(jìn)行比較。愛掏網(wǎng) - it200.com由于它們現(xiàn)在等效,因此比較結(jié)果是0。愛掏網(wǎng) - it200.com
結(jié)論
toUpperCase()方法是一種JavaScript字符串轉(zhuǎn)換方法,可以將所有小寫字母轉(zhuǎn)換為大寫字母,并且支持Unicode字符。愛掏網(wǎng) - it200.com在進(jìn)行字符串比較時(shí),必須注意字符串的大小寫,以確保結(jié)果正確。愛掏網(wǎng) - it200.com