String 字串對(duì)象
String 字串物件
(1)String 的屬性
該物件只有一個(gè)屬性,即length,表示字串中的字元數(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):
##存取字串物件的方法:
使用String 物件的toUpperCase() 方法將字串小寫(xiě)字母轉(zhuǎn)換為大寫(xiě):var mystr="Hello world!"; var mynum=mystr.toUpperCase();以上程式碼執(zhí)行之後,mynum 的值是:HELLO WORLD!
String 的方法
String 物件共有19 個(gè)內(nèi)建方法,主要包括字串在頁(yè)面中的顯示、字體大小、字體顏色、字元的搜尋以及字元的大小寫(xiě)轉(zhuǎn)換等功能,以下是一些常用的:
charAt(n) :傳回該字串第n 位元的單一字元。 (從 0 開(kāi)始計(jì)數(shù))
charCodeAt(n) :傳回該字串第 n 位元的單一字元的 ASCII 碼。
indexOf() :用法:string_1.indexOf(string_2,n); 從字串string_1 的第n 位開(kāi)始搜索,查找string_2,返回查找到的位置,如果找不到,則傳回-1,其中n 可以不填,預(yù)設(shè)從第0 位開(kāi)始查找。
lastIndexOf() :跟 indexOf() 相似,不過(guò)是從後邊開(kāi)始找。
split('分隔符號(hào)') :將字串依照指定的分隔符號(hào)分離開(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://www.miracleart.cn") + "</p>") </script> </body> </html>
#