String 字符串對(duì)象
String 字符串對(duì)象
(1)String 的屬性
該對(duì)象只有一個(gè)屬性,即 length,表示字符串中的字符個(gè)數(shù),包括所有的空格和符號(hào):
var test_var = "I love You!"; document.write(test_var.length);
顯示結(jié)果是“11”因?yàn)樽址L(zhǎng)度將符號(hào)和空格也計(jì)算在內(nèi):
訪問(wèn)字符串對(duì)象的方法:
使用 String 對(duì)象的 toUpperCase() 方法來(lái)將字符串小寫(xiě)字母轉(zhuǎn)換為大寫(xiě):
var mystr="Hello world!"; var mynum=mystr.toUpperCase();
以上代碼執(zhí)行后,mynum 的值是:HELLO WORLD!
(2)String 的方法
String 對(duì)象共有 19 個(gè)內(nèi)置方法,主要包括字符串在頁(yè)面中的顯示、字體大小、字體顏色、字符的搜索以及字符的大小寫(xiě)轉(zhuǎn)換等功能,下面是一些常用的:
charAt(n) :返回該字符串第 n 位的單個(gè)字符。(從 0 開(kāi)始計(jì)數(shù))
charCodeAt(n) :返回該字符串第 n 位的單個(gè)字符的 ASCII 碼。
indexOf() :用法:string_1.indexOf(string_2,n); 從字符串 string_1 的第 n 位開(kāi)始搜索,查找 string_2,返回查找到的位置,如果未找到,則返回 -1,其中 n 可以不填,默認(rèn)從第 0 位開(kāi)始查找。
lastIndexOf() :跟 indexOf() 相似,不過(guò)是從后邊開(kāi)始找。
split('分隔符') :將字符串按照指定的分隔符分離開(kāi),返回一個(gè)數(shù)組,例如:'1&2&345&678'.split('&');返回?cái)?shù)組:1,2,345,678。
substring(n,m) :返回原字符串從 n 位置到 m 位置的子串。
substr(n,x) :返回原字符串從 n 位置開(kāi)始,長(zhǎng)度為 x 的子串。
toLowerCase() :返回把原字符串所有大寫(xiě)字母都變成小寫(xiě)的字符串。
toUpperCase() :返回把原字符串所有小寫(xiě)字母都變成大寫(xiě)的字符串。
計(jì)算字符串的長(zhǎng)度
<html> <body> <script type="text/javascript"> var txt="Hello World!" document.write(txt.length) </script> </body> </html>
為字符串添加樣式
<html> <body> <script type="text/javascript"> var txt="Hello World!" document.write("<p>Big: " + txt.big() + "</p>") document.write("<p>Small: " + txt.small() + "</p>") document.write("<p>Bold: " + txt.bold() + "</p>") document.write("<p>Italic: " + txt.italics() + "</p>") document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>") document.write("<p>Fixed: " + txt.fixed() + "</p>") document.write("<p>Strike: " + txt.strike() + "</p>") document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>") document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>") document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>") document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>") document.write("<p>Subscript: " + txt.sub() + "</p>") document.write("<p>Superscript: " + txt.sup() + "</p>") document.write("<p>Link: " + txt.link("http://m.miracleart.cn") + "</p>") </script> </body> </html>