Javascript類型系統(tǒng)之String字符串類型詳解
javascript沒有表示單個(gè)字符的字符型,只有字符串String類型,字符型相當(dāng)于僅包含一個(gè)字符的字符串
字符串String是javascript基本數(shù)據(jù)類型,同時(shí)javascript也支持String對(duì)象,它是一個(gè)原始值的包裝對(duì)象。在需要時(shí),javascript會(huì)自動(dòng)在原始形式和對(duì)象形式之間轉(zhuǎn)換。本文將介紹字符串String原始類型及String包裝對(duì)象
定義
字符串String類型是由引號(hào)括起來的一組由16位Unicode字符組成的字符序列
字符串類型常被用于表示文本數(shù)據(jù),此時(shí)字符串中的每個(gè)元素都被視為一個(gè)代碼點(diǎn)。每個(gè)元素都被認(rèn)為占有此序列中的一個(gè)位置,用非負(fù)數(shù)值索引這些位置。首字符從位置0開始,第二個(gè)字符在位置1,依次類推
字符串的長(zhǎng)度即其中元素的個(gè)數(shù)(比如,16 位值)??兆址L(zhǎng)度為零,因而不包含任何元素
Unicode編碼
所有字符都可以寫成'\uxxxx'的形式,其中xxxx代表該字符的Unicode編碼。比如,\u00A9代表版權(quán)符號(hào)
var s = '\u00A9'; s // "©"
若一個(gè)字符串包含實(shí)際的文本數(shù)據(jù),每個(gè)元素都被認(rèn)為是一個(gè)單獨(dú)的UTF-16單元。每個(gè)字符在JavaScript內(nèi)部都是以16位(即2個(gè)字節(jié))的UTF-16格式儲(chǔ)存
但UTF-16有兩種長(zhǎng)度:對(duì)于U+0000到U+FFFF之間的字符,長(zhǎng)度為16位(即2個(gè)字節(jié));對(duì)于U+10000到U+10FFFF之間的字符,長(zhǎng)度為32位(即4個(gè)字節(jié)),而且前兩個(gè)字節(jié)在0xD800到0xDBFF之間,后兩個(gè)字節(jié)在0xDC00到0xDFFF之間
舉例來說,U+1D306對(duì)應(yīng)的字符"𝌆",寫成UTF-16就是0xD834 0xDF06。瀏覽器會(huì)正確將這四個(gè)字節(jié)識(shí)別為一個(gè)字符,但是javascript內(nèi)部的字符長(zhǎng)度總是固定為16位,會(huì)把這四個(gè)字節(jié)視為兩個(gè)字符
var s = '\uD834\uDF06'; s // "𝌆" s.length // 2
對(duì)于U+10000到U+10FFFF的4字節(jié)Unicode字符,javascript總是視為兩個(gè)字符(字符length屬性為2)
引號(hào)
字符串String是由雙引號(hào)(")或單引號(hào)(')聲明的。而Java則是用雙引號(hào)聲明字符串,用單引號(hào)聲明字符。由于ECMAScript 沒有字符類型,所以可使用這兩種表示法中的任何一種,但左右引號(hào)必須匹配
//正確 var sColor1 = "red"; var sColor2 = 'red'; //錯(cuò)誤 var sColor1 = "red'; var sColor2 = 'red";
由單引號(hào)定界的字符串中可以包含雙引號(hào),由雙引號(hào)定界的字符串也可以包含單引號(hào)
'key = "value"' "It's a long journey"
javascript代碼可能會(huì)夾雜HTML代碼的字符串,HTML代碼也會(huì)夾雜javascript代碼。因此,最好在javascript和HTML代碼中各自使用獨(dú)自的引號(hào)風(fēng)格
javascript中使用單引號(hào)表示字符串,在HTML事件處理程序中使用雙引號(hào)表示字符串
<button onclick = "alert('thanks')">click me</button>
反斜線
如果想在單引號(hào)定界的字符串中使用單引號(hào),或在雙引號(hào)定界的字符串中使用雙引號(hào),則需要使用反斜線(\)
常見情況是英文縮寫和所有格寫法的撇號(hào)和單引號(hào)是同一個(gè)字符,所以這時(shí)必須使用反斜線(\)來轉(zhuǎn)義撇號(hào)
'Wouldn\'t you prefer this book?' //"Wouldn't you prefer this book?" 'Did she say \'Hello\'?' //"Did she say 'Hello'?" "Did she say \"Hello\"?" //"Did she say "Hello"?"
多行字符
字符串默認(rèn)只能寫在一行內(nèi),分成多行將會(huì)報(bào)錯(cuò)
//報(bào)錯(cuò) Uncaught SyntaxError: Invalid or unexpected token
'a
b
c';
在ECMAScript3中,字符串必須寫在一行中
在ECMAScript5中,字符串可以拆分成數(shù)行,每行必須以反斜線(\)結(jié)束
如果希望在字符串直接量中另起一行,可以使用轉(zhuǎn)義字符\n
//"onelongline" 'one\ long\ line' /*"two lines"*/ 'two\nlines'
轉(zhuǎn)義字符
在javascript字符串,反斜線(\)有著特殊的用途,反斜線符號(hào)后加一個(gè)字符,就不表示它們的字面含義,用來表示一些特殊字符,稱為轉(zhuǎn)義字符
\0 空字節(jié)
\n 換行
\t 制表
\b 空格
\r 回車
\f 進(jìn)紙
\\ 斜杠
\' 單引號(hào)
\" 雙引號(hào)
\xnn 以十六進(jìn)制nn表示一個(gè)字符(n為0-f),如\x41表示'A'
\unnnn 以十六進(jìn)制nnnn表示一個(gè)Unicode字符(n為0-f),如\u03a3表示希臘字符ε
如果在非特殊字符前面使用反斜杠,則反斜杠會(huì)被省略
'\a' // "a"
如果字符串需要包含反斜杠,則反斜杠前面需要再加一個(gè)反斜杠,用來對(duì)自身轉(zhuǎn)義
"Prev \\ Next" // "Prev \ Next"
特點(diǎn)
javascript中的字符串是不可變的。一旦字符串被創(chuàng)建,就永遠(yuǎn)無法改變它。要改變某個(gè)變量保存的字符串,首先要銷毀原來的字符串,然后再用另一個(gè)包含新值的字符串填充該變量
可以通過+運(yùn)算符連接其他字符串來創(chuàng)建一個(gè)新字符串
var lang = "java"; lang = lang + "script"; //'javascript'
以上代碼的實(shí)際過程是:首先創(chuàng)建一個(gè)能夠容納10個(gè)字符的新字符串,然后在這個(gè)字符串中填充'java'和'script',最后一步是銷毀原來的字符串'java'和'script',因?yàn)檫@兩個(gè)字符串已經(jīng)沒用了
這個(gè)過程在后臺(tái)發(fā)生,也是在某些舊版本瀏覽器(IE6)拼接字符串速度慢的原因,但瀏覽器后面版本已經(jīng)解決了這個(gè)低效率問題
轉(zhuǎn)字符串
把一個(gè)值轉(zhuǎn)換為字符串有兩種方式,toString()和String()
[注意]可以使用空字符串"" + 某個(gè)值,將該值轉(zhuǎn)換為字符串
toString()
第一種是使用幾乎每個(gè)值都有的toString()方法,這個(gè)方法返回相應(yīng)值的字符串表現(xiàn)
[注意]undefined和null沒有該方法
undefined.toString();//錯(cuò)誤 null.toString();//錯(cuò)誤 true.toString();//'true' false.toString();//'false' 'abc'.toString();//'abc' 1.23.toString();//'1.23' ({}).toString();//[object Object] [1,2,3,4].toString();//'1,2,3,4' (new Date()).toString();//"Sun Jun 05 2016 10:04:53 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)" /ab/i.toString();//'/ab/i'
String()
在不知道要轉(zhuǎn)換的值是不是undefined或null時(shí),可以使用轉(zhuǎn)型函數(shù)String()
轉(zhuǎn)型函數(shù)String()遵循下列規(guī)則:
【1】如果值是null,則返回'null';如果值是undefined,則返回'undefined'
【2】如果值不是null或undefined,則調(diào)用toString()方法并返回原始類型值
【3】若使用toString()方法返回的是對(duì)象,則再調(diào)用valueOf()方法返回原始類型值,若使用valueOf()方法返回的是對(duì)象,會(huì)報(bào)錯(cuò)
// "3" String({toString: function () { return 3; } }) // "[object Object]" String({valueOf: function () { return 2; } }) // "3" String({ valueOf: function () { return 2; }, toString: function () { return 3; } })
長(zhǎng)度屬性
字符串String類型的每個(gè)實(shí)例都有一個(gè)length屬性,表示字符串中的字符個(gè)數(shù)。由于字符串是不可變的,所以字符串的長(zhǎng)度也不可變
字符串的length屬性不會(huì)在for/in循環(huán)中枚舉,也不能通過delete操作符刪除
[注意]對(duì)于字符串s來說,最后一個(gè)字符的索引是s.length - 1
var str = "test"; console.log(str.length);//4 str.length = 6; console.log(str,str.length);//"test",4
實(shí)例方法
對(duì)象通用方法
String類型是與字符串對(duì)應(yīng)的包裝類型,繼承了Object對(duì)象的通用方法toString()、toLocaleString()、valueOf()這三個(gè)方法
【toString()】
toString()方法返回string的原始字符串值
【toLocaleString()】
toLocaleString()方法返回string的原始字符串值
【valueOf()】
valueOf()方法返回string的原始字符串值
console.log("test".valueOf());//"test" console.log("test".toString());//"test" console.log("test".toLocaleString());//"test"
訪問字符方法
字符串的訪問字符方法總共有chartAt()、中括號(hào)[]、charCodeAt()和fromCharCode()四種
【chartAt()】
charAt()方法接收一個(gè)基于0的字符位置的參數(shù),返回指定位置的字符。當(dāng)參數(shù)為空或NaN時(shí),默認(rèn)參數(shù)為0;當(dāng)參數(shù)超出范圍時(shí),則返回一個(gè)空字符串
var str = "hello"; console.log(str.charAt(1));//e console.log(str.charAt(-1));//'' console.log(str.charAt(10));//'' console.log(str.charAt());//h console.log(str.charAt(NaN));//h
charAt()方法涉及到Number()函數(shù)的隱式類型轉(zhuǎn)換,如果轉(zhuǎn)換為數(shù)值,則按照上述規(guī)則輸出字符串;如果轉(zhuǎn)換為NaN,則輸出第0個(gè)字符
var str = "hello"; console.log(str.charAt(true));//'e' console.log(str.charAt(false));//'h' console.log(str.charAt('abc'));//'h' console.log(str.charAt({}));//'h' console.log(str.charAt([2]));//'l'
[注意]x.charAt(pos)與x.substring(pos, pos+1)、x.substr(pos,1)、x.slice(pos,pos+1)的結(jié)果相等
var str = "hello"; console.log(str.charAt(1));//'e' console.log(str.substring(1,2));//'e' console.log(str.slice(1,2));//'e' console.log(str.substr(1,1));//'e'
【中括號(hào)】
ECMAScript5定義了另一個(gè)訪問字符的方法,使用方括號(hào)加數(shù)字索引來訪問字符串中的特定字符。如果參數(shù)超出范圍或是NaN時(shí),則輸出undefined;沒有參數(shù)時(shí),會(huì)報(bào)錯(cuò);該方法沒有Number()轉(zhuǎn)型函數(shù)的隱式類型轉(zhuǎn)換,但參數(shù)為單數(shù)值數(shù)組時(shí)可轉(zhuǎn)換為數(shù)值
[注意]IE7-瀏覽器不支持
var str = "hello"; console.log(str[0]);//h console.log(str[[1]]);//e console.log(str[false]);//undefined console.log(str[-1]);//undefined console.log(str[NaN]);//undefined console.log(str[]);//報(bào)錯(cuò)
【charCodeAt()】
charCodeAt()方法類似于charAt()方法,接收一個(gè)基于0的字符位置的參數(shù),但返回的是指定位置的字符16位Unicode編碼。返回值是一個(gè)16位的整數(shù),在0-65535之間,即0x0000-0xffff之間
參數(shù)為空或NaN時(shí),默認(rèn)參數(shù)為0;當(dāng)參數(shù)超出范圍時(shí),則返回NaN
var str = "hello"; console.log(str.charCodeAt());//104 console.log(str.charCodeAt(0));//104 console.log(str.charCodeAt(1));//101 console.log(str.charCodeAt(-1));//NaN console.log(str.charCodeAt(10));//NaN console.log(str.charCodeAt(NaN));//104
同樣地,charCodeAt()方法涉及到Number()函數(shù)的隱式類型轉(zhuǎn)換,如果轉(zhuǎn)換為數(shù)值,則按照上述規(guī)則輸出相應(yīng)值;如果轉(zhuǎn)換為NaN,則輸出第0個(gè)字符的字符編碼
var str = "hello"; console.log(str.charCodeAt(true));//101 console.log(str.charCodeAt(false));//104 console.log(str.charCodeAt('abc'));//104 console.log(str.charCodeAt({}));//104 console.log(str.charCodeAt([2]));//l08
【fromCharCode()】
String構(gòu)造函數(shù)本身有一個(gè)靜態(tài)方法:fromCharCode()。這個(gè)方法的任務(wù)是接收一個(gè)或多個(gè)字符編碼,然后把它們轉(zhuǎn)換成一個(gè)字符串。從本質(zhì)上看,這個(gè)方法與實(shí)例方法charCodeAt()執(zhí)行的是相反的操作。若參數(shù)為空為NaN時(shí),則返回空字符串;若參數(shù)超出0-65535的范圍,則輸出字符不可控
console.log(String.fromCharCode(104,101,108,108,111));//'hello' console.log(String.fromCharCode(0x6211,0x662f,0x5c0f,0x706b,0x67f4));//'我是小火柴' console.log(String.fromCharCode());//'' console.log(String.fromCharCode(NaN));//'' console.log(String.fromCharCode(-1)); console.log(String.fromCharCode(65560));
如果一個(gè)字符占用四字節(jié),則需要拆成兩個(gè)字符表示
console.log(String.fromCharCode(0xD842, 0xDFB7)); // "𠮷"
字符串拼接
關(guān)于字符串拼接共有concat()和加號(hào)+兩種方法
【concat()】
concat()方法用于將一個(gè)或多個(gè)字符串拼接起來,返回拼接得到的新字符串,而原字符串不發(fā)生改變。若參數(shù)(第一個(gè)參數(shù)除外)不是字符串,則通過String()方法隱式轉(zhuǎn)換為字符串,再進(jìn)行字符串拼接
var stringValue = 'hello '; var result = stringValue.concat('world','!'); console.log(result);//'hello world!' console.log(stringValue);//'hello'
[注意]第一個(gè)參數(shù)只能是字符串,如果是其他類型(數(shù)組除外)則報(bào)錯(cuò)
(1).concat('2');//報(bào)錯(cuò)
(true).concat('false');//報(bào)錯(cuò)
({}).concat('abc');//報(bào)錯(cuò)
[注意]由于數(shù)組也存在concat()方法,參數(shù)會(huì)按照首先出現(xiàn)的參數(shù)是數(shù)組還是字符串來決定如何轉(zhuǎn)換
'1,2,3,'.concat([4,5]);//'1,2,3,4,5'
[1,2,3].concat(',4,5');//[1, 2, 3, ",4,5"]
【加號(hào)運(yùn)算符(+)】
雖然concat()是專門用來拼接字符串的方法,但實(shí)踐中使用更多的還是加號(hào)運(yùn)算符(+)。使用加號(hào)運(yùn)算符在許多時(shí)候都比concat()簡(jiǎn)單易行
var stringValue = 'hello '; console.log(stringValue.concat('world','!'));//'hello world!' console.log(stringValue + 'world' + '!');//'hello world!'
[注意]當(dāng)操作數(shù)其中一個(gè)是字符串,或者對(duì)象轉(zhuǎn)換為字符串時(shí),才進(jìn)行字符串拼接
1 + 2;//3 '1' + 2;//'12' var o = {valueOf:function(){return '1';}}; o + 2;//'12' var o = {valueOf:function(){return 1;}}; o + 2;//3
創(chuàng)建子字符串
創(chuàng)建子字符串共有slice()、substr()和substring()三種方法
【slice()】
slice(start,end)方法需要兩個(gè)參數(shù)start和end,返回這個(gè)字符串中從start位置的字符到(但不包含)end位置的字符的一個(gè)子字符串;如果end為undefined或不存在,則返回從start位置到字符串結(jié)尾的所有字符
如果start是負(fù)數(shù),則start = max(length + start,0)
如果end是負(fù)數(shù),則end = max(length + end,0)
start和end無法交換位置
var stringValue = 'hello world'; console.log(stringValue.slice());//'hello world' console.log(stringValue.slice(2));//'llo world' console.log(stringValue.slice(2,undefined));//'llo world' console.log(stringValue.slice(2,-5));//'llo ' console.log(stringValue.slice(2,-20));//'' console.log(stringValue.slice(20));//'' console.log(stringValue.slice(-2,2));//'' console.log(stringValue.slice(-2,-20));//'' console.log(stringValue.slice(-2,20));//'ld' console.log(stringValue.slice(-20,2));//'he' console.log(stringValue.slice(-20,-2));//'hello wor'
slice()方法涉及到Number()轉(zhuǎn)型函數(shù)的隱式類型轉(zhuǎn)換,當(dāng)start被轉(zhuǎn)換為NaN時(shí),相當(dāng)于start = 0;當(dāng)end被轉(zhuǎn)換為NaN時(shí)(end為undefined除外),則輸出空字符串
var stringValue = 'hello world'; console.log(stringValue.slice(NaN));//'hello world' console.log(stringValue.slice(0,NaN));//'' console.log(stringValue.slice(true,[3]));//'el' console.log(stringValue.slice(null,undefined));//'hello world' console.log(stringValue.slice({}));//'hello world' console.log(stringValue.slice('2',[5]));//'llo'
【substring()】
substring(start,end)方法需要兩個(gè)參數(shù)start和end,返回這個(gè)字符串中從start位置的字符到(但不包含)end位置的字符的一個(gè)子字符串;如果end為undefined或不存在,則返回從start位置到字符串結(jié)尾的所有字符
如果任一參數(shù)是NaN或負(fù)數(shù),則被0取代
如果任一參數(shù)大于字符串長(zhǎng)度,則被字符串長(zhǎng)度取代
如果start 大于 end,則交換它們的值
var stringValue = 'hello world'; console.log(stringValue.substring());//'hello world' console.log(stringValue.substring(2));//'llo world' console.log(stringValue.substring(2,undefined));//'llo world' console.log(stringValue.substring(20));//'' console.log(stringValue.substring(-2,2));//'he' console.log(stringValue.substring(NaN,2));//'he' console.log(stringValue.substring(-2,20));//'hello world' console.log(stringValue.substring(3,2));//'l' console.log(stringValue.substring(3,NaN));//'hel' console.log(stringValue.substring(-20,2));//'he' console.log(stringValue.substring(-20,-2));//''
同樣地,substring()方法也涉及到Number()轉(zhuǎn)型函數(shù)的隱式類型轉(zhuǎn)換
var stringValue = 'hello world'; console.log(stringValue.substring(true,[3]));//'el' console.log(stringValue.substring(null,undefined));//'hello world' console.log(stringValue.substring({}));//'hello world' console.log(stringValue.substring('2',[5]));//'llo'
【substr()】
substr(start,end)方法需要兩個(gè)參數(shù)start和end,end代表返回的子字符串的字符個(gè)數(shù);該方法返回這個(gè)字符串中從start位置的字符開始的end個(gè)字符的一個(gè)子字符串;如果end為undefined或不存在,則返回從start位置到字符串結(jié)尾的所有字符
如果start是負(fù)數(shù),則start = max(length + start,0)
如果start是NaN,則相當(dāng)于start = 0
如果end是負(fù)數(shù)或NaN,則end = 0,因此會(huì)返回空字符串
start和end無法交換位置
[注意]該方法不是ECMAScript標(biāo)準(zhǔn),已經(jīng)被棄用
[注意]IE8-瀏覽器在處理向substr()傳遞負(fù)值的情況時(shí)存在問題,它會(huì)返回原始的字符串
var stringValue = 'hello world'; console.log(stringValue.substr());//'hello world' console.log(stringValue.substr(2));//'llo world' console.log(stringValue.substr(2,undefined));//'llo world' console.log(stringValue.substr(2,NaN));//'' console.log(stringValue.substr(NaN,2));//'he' console.log(stringValue.substr(20));//'' console.log(stringValue.substr(-2,3));//'ld' console.log(stringValue.substr(-2,20));//'ld' console.log(stringValue.substr(-20,2));//'he' console.log(stringValue.substr(-20,-2));//'' console.log(stringValue.substr(2,5));//llo w
同樣地,substr()方法也涉及到Number()轉(zhuǎn)型函數(shù)的隱式類型轉(zhuǎn)換
var stringValue = 'hello world'; console.log(stringValue.substr(true,[3]));//'el' console.log(stringValue.substr(null,undefined));//'hello world' console.log(stringValue.substr({}));//'hello world' console.log(stringValue.substr('2',[5]));//'llo w'
字符串位置
有兩個(gè)從字符串中查找子字符串位置的方法:indexOf()和lastIndexOf()
【indexOf()】
indexOf(searchString,start)方法接收searchString和start兩個(gè)參數(shù),返回searchString首次出現(xiàn)的位置,如果沒有找到則返回-1
該方法會(huì)隱式調(diào)用String()轉(zhuǎn)型函數(shù),將searchString非字符串值轉(zhuǎn)換為字符串;隱式調(diào)用Number()轉(zhuǎn)型函數(shù),將start非數(shù)字值(undefined除外)轉(zhuǎn)換為數(shù)值
searchString表示要搜索的子字符串;start表示該搜索的開始位置,若忽略該參數(shù)或該參數(shù)為undefined、NaN或負(fù)數(shù)時(shí),start = 0
var string = 'hello world world'; console.log(string.indexOf('ld'));//9 console.log(string.indexOf('ld',undefined));//9 console.log(string.indexOf('ld',NaN));//9 console.log(string.indexOf('ld',-1));//9 console.log(string.indexOf('ld',10));//15 console.log(string.indexOf('ld',[10]));//15 console.log(string.indexOf('true',[10]));//-1 console.log(string.indexOf(false,[10]));//-1
【lastIndexOf()】
lastIndexOf(searchString,start)方法接收searchString和start兩個(gè)參數(shù),返回searchString最后一次出現(xiàn)的位置,如果沒有找到則返回-1
同樣地,該方法會(huì)隱式調(diào)用String()轉(zhuǎn)型函數(shù),將searchString非字符串值轉(zhuǎn)換為字符串;隱式調(diào)用Number()轉(zhuǎn)型函數(shù),將start非數(shù)字值(undefined除外)轉(zhuǎn)換為數(shù)值
searchString表示要搜索的子字符串;start表示該搜索的開始位置,若忽略該參數(shù)或該參數(shù)為undefined、NaN時(shí),start = length - 1
[注意]與indexOf()方法不同,若start為負(fù)數(shù),則該方法返回-1
var string = 'hello world world'; console.log(string.indexOf('ld'));//9 console.log(string.indexOf('ld',undefined));//9 console.log(string.indexOf('ld',NaN));//9 console.log(string.indexOf('ld',-1));//-1 console.log(string.indexOf('ld',10));//15 console.log(string.indexOf('ld',[10]));//15 console.log(string.indexOf('true',[10]));//-1 console.log(string.indexOf(false,[10]));//-1
【tips】查找出字符串所有符合條件的子字符串
可以通過循環(huán)調(diào)用indexOf()或lastIndexOf()來找到所有匹配的子字符串
function allIndexOf(str,value){ var result = []; var pos = str.indexOf(value); while(pos > -1){ result.push(pos); pos = str.indexOf(value,pos+value.length); } return result; } console.log(allIndexOf('helllhelllhelll','ll'));//[2,7,12]
【trim()】
ECMAScript5為所有字符串定義了trim()方法。這個(gè)方法會(huì)創(chuàng)建一個(gè)字符串的副本,刪除前置及后綴的所有空白字符,然后返回結(jié)果
由于trim()方法返回的是字符串的副本,所以原始字符串中的前置及后綴空格會(huì)保持不變
[注意]IE8-瀏覽器不支持
var string = ' hello world '; console.log(string.trim());//'hello world' console.log(string);//' hello world '
空白字符不僅僅包括空格,還包括制表符(\t)、換行符(\n)和回車符(\r)
'\r\nabc \t'.trim() // 'abc'
此外,firefox、safari和webkit還支持非標(biāo)準(zhǔn)的trimRight()用于刪除字符串結(jié)尾的空白字符
var string = ' hello world '; console.log(string.trimRight());//' hello world';
【tips】用trim()來判斷輸入的字符是否為空
if(usename.trim().length){ alert('correct'); }else{ alert('error'); }
【tips】用正則表達(dá)式模擬trim()
function fnTrim(str){ return str.replace(/^\s+|\s+$/,'') } console.log(fnTrim(' hello world '));//'hello world'
大小寫轉(zhuǎn)換
ECMAScript中涉及字符串大小寫轉(zhuǎn)換的方法有4個(gè):toLowerCase()、toLocaleLowerCase()、toUpperCase()、toLocaleUpperCase()
toLowerCase()和toUpperCase()是兩個(gè)經(jīng)典的方法,借鑒自java.lang.String中的同名方法。而toLocaleLowerCase()和toLocaleUpperCase()方法則是針對(duì)特定地區(qū)的實(shí)現(xiàn),對(duì)有些地區(qū)來說,針對(duì)地區(qū)的方法與其通用方法得到的結(jié)果相同,但少數(shù)語言(如土耳其語)會(huì)為Unicode大小寫轉(zhuǎn)換應(yīng)用特殊的規(guī)則,這時(shí)候就必須使用針對(duì)地區(qū)的方法來保證實(shí)現(xiàn)正確的轉(zhuǎn)換
【toUpperCase()】
toUpperCase()方法將字符串轉(zhuǎn)換成大寫
【toLowerCase()】
toLowerCase()方法將字符串轉(zhuǎn)換成小寫
【toLocaleUpperCase()】
toLocaleUpperCase()方法將字符串轉(zhuǎn)換成大寫(針對(duì)地區(qū))
【toLocaleLowerCase()】
toLocaleLowerCase()方法將字符串轉(zhuǎn)換成小寫(針對(duì)地區(qū))
[注意]在不知道自己的代碼將在哪個(gè)語言環(huán)境中運(yùn)行的情況下,使用針對(duì)地區(qū)的方法更穩(wěn)妥
var string = 'Hello World'; console.log(string.toLowerCase());//hello world console.log(string.toLocaleLowerCase());//hello world console.log(string.toUpperCase());//HELLO WORLD console.log(string.toLocaleUpperCase());//HELLO WORLD
這4種方法均不支持String()隱式類型轉(zhuǎn)換,只支持字符串類型
(true).toLowerCase();//報(bào)錯(cuò)
(2).toLocaleLowerCase();//報(bào)錯(cuò)
({}).toUpperCase();//報(bào)錯(cuò)
([]).toLocaleUpperCase();//報(bào)錯(cuò)
[注意]大小寫轉(zhuǎn)換方法可以連續(xù)使用
var string = 'Hello World'; console.log((string.toUpperCase()).toLowerCase());//hello world
【localeCompare()】
localeCompare()方法用于比較兩個(gè)字符串,遵循下列規(guī)則
【1】如果字符串在字母表中應(yīng)該排在字符串參數(shù)之前,則返回一個(gè)負(fù)數(shù)(大多數(shù)情況下為-1)
【2】如果字符串等于字符串參數(shù),則返回0
【3】如果字符串在字母表中應(yīng)該排在字符串參數(shù)之后,則返回一個(gè)正數(shù)(大多數(shù)情況下為1)
var stringValue = 'yellow'; console.log(stringValue.localeCompare('brick'));//1 'y'> 'b' console.log(stringValue.localeCompare('yellow'));//0 'yellow' == 'yellow' console.log(stringValue.localeCompare('zoo'));//-1 'yellow' < 'zoo'
[注意]雖然在字母表中大寫字母在小寫字母的前面,所以大寫字母 < 小寫字母。但localeCompare()方法會(huì)考慮自然語言的排序情況,把'B'排在'a'的前面
console.log('B'.localeCompare('a'));//1 console.log('B' > 'a');//false console.log('b'.localeCompare('a'));//1 console.log('b' > 'a');//true
以上所述是小編給大家介紹的Javascript類型系統(tǒng)之String字符串類型詳解的相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- JS 對(duì)象(Object)和字符串(String)互轉(zhuǎn)方法
- JavaScript截取字符串的Slice、Substring、Substr函數(shù)詳解和比較
- js String對(duì)象中常用方法小結(jié)(字符串操作)
- js字符串的各種格式的轉(zhuǎn)換 ToString,F(xiàn)ormat
- js substring()字符串截取函數(shù)
- JavaScript字符串String和Array操作的有趣方法
- Javascript String 字符串操作包
- 幾個(gè)常用的JavaScript字符串處理函數(shù) - split()、join()、substring()和indexOf()
- javaScript字符串工具類StringUtils詳解
- JavaScript的String字符串對(duì)象常用操作總結(jié)
- js字符串類型String常用操作實(shí)例總結(jié)
相關(guān)文章
JavaScript運(yùn)動(dòng)框架 解決速度正負(fù)取整問題(一)
這篇文章主要為大家詳細(xì)介紹了JavaScript運(yùn)動(dòng)框架的第一部分,解決速度正負(fù)取整問題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05分享JavaScript監(jiān)聽全部Ajax請(qǐng)求事件的方法
最近在做一個(gè)小項(xiàng)目,引入了第三方j(luò)s文件,這個(gè)文件會(huì)調(diào)用XMLHttpRequest向服務(wù)器發(fā)送 Ajax請(qǐng)求,但是我有需要監(jiān)聽其Ajax請(qǐng)求的某些事件,以便額外地執(zhí)行其他腳本。于是稍微看了看監(jiān)聽 Ajax請(qǐng)求的事件方法,在這里分享給大家。有需要的朋友們可以參考借鑒。2016-08-08javascript刪除option選項(xiàng)的多種方法總結(jié)
這篇文章主要是對(duì)javascript刪除option選項(xiàng)的多種方法進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-11-11drag-and-drop實(shí)現(xiàn)圖片瀏覽器預(yù)覽
chrome的drag and drop API,它能將本地的圖片放到瀏覽器中進(jìn)行預(yù)覽,猜想一下當(dāng)我們把圖片拖拽到瀏覽器里會(huì)發(fā)生什么事情,你的瀏覽器試圖打開一個(gè)新的頁面并加載這個(gè)圖片。這篇文章給我們介紹drag-and-drop實(shí)現(xiàn)圖片瀏覽器預(yù)覽,需要的朋友可以參考下2015-08-08