String 字串對象

String 字串物件

(1)String 的屬性

該物件只有一個屬性,即length,表示字串中的字元數,包括所有的空格和符號:

var test_var = "I love You!";
document.write(test_var.length);

顯示結果是「11」因為字串長度將符號和空格也計算在內:

QQ截图20161012162429.png

##存取字串物件的方法

使用String 物件的toUpperCase() 方法將字串小寫字母轉換為大寫:

var mystr="Hello world!";
var mynum=mystr.toUpperCase();

以上程式碼執行之後,mynum 的值是:HELLO WORLD!


(2)

String 的方法

String 物件共有19 個內建方法,主要包括字串在頁面中的顯示、字體大小、字體顏色、字元的搜尋以及字元的大小寫轉換等功能,以下是一些常用的:

charAt(n) :傳回該字串第n 位元的單一字元。 (從 0 開始計數)

charCodeAt(n) :傳回該字串第 n 位元的單一字元的 ASCII 碼。

indexOf() :用法:string_1.indexOf(string_2,n); 從字串string_1 的第n 位開始搜索,查找string_2,返回查找到的位置,如果找不到,則傳回-1,其中n 可以不填,預設從第0 位開始查找。

lastIndexOf() :跟 indexOf() 相似,不過是從後邊開始找。

split('分隔符號') :將字串依照指定的分隔符號分離開,傳回一個數組,例如:'1&2&345&678'.split('&');傳回數組:1,2,345,678。

substring(n,m) :傳回原字串從 n 位置到 m 位置的子字串。

substr(n,x) :傳回原始字串從 n 位置開始,長度為 x 的子字串。

toLowerCase() :傳回把原始字串所有大寫字母變成小寫的字串。

toUpperCase() :傳回把原始字串所有小寫字母都變成大寫的字串。

計算字串的長度

<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("//m.sbmmt.com") + "</p>")
</script>
</body>
</html>


#

繼續學習
||
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>string对象 </title> <script type="text/javascript"> var message="I love JavaScript!"; var mychar=message.toLowerCase(); document.write("字符串为:"+mychar+"<br>"); </script> </head> <body> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!