Javascript:字串對象(string)的基本操作
1.擷取字串的長度:
var s = Hello world;document.write(length:+s.length);
2.為字串添加各種樣式,如:
var txt = Some words;document.write(
Big: + txt.big() +
) document.write(
Small: + txt.small() +
) document.write(
Bold: + txt.bold() +
) document.write(
Italic: + txt.italics() +
) document.write(
Blink: + txt.blink() + (does not work in IE)
) document.write(
Fixed: + txt.fixed() +
) document.write(
Strike: + txt.strike() +
) document.write(
Fontcolor: + txt.fontcolor(Red) +
) document.write(
Fontsize: + txt.fontsize(16) +
) document.write(
Link: + txt.link(http://www.w3school.com.cn) +
)3.擷取字串中部分內容首次出現的位置:
var hw_text = Hello world;document.write(hw_text.indexOf(Hello)+);document.write(hw_text.indexOf(world)+);document.write(hw_text.indexOf(abc)+);
4.內容替換:
var str=Visit Microsoft!document.write(str.replace(/Microsoft/,W3School))
:
範例程式碼:
(一)length屬性:擷取字串的長度
Hello world, Hello javascript!
<script> var s = document.getElementById(hw).innerHTML; document.write(length:+s.length); </script>(二)為字串添加樣式
對字串調用樣式的相關方法時,會自動拼接相應的html標籤
some words
Call txt.big()<script> var txt = document.getElementById(hw_02).innerHTML; document.write(
Big: + txt.big() +
) document.write(
Small: + txt.small() +
) document.write(
Bold: + txt.bold() +
) document.write(
Italic: + txt.italics() +
) document.write(
Blink: + txt.blink() + (does not work in IE)
) document.write(
Fixed: + txt.fixed() +
) document.write(
Strike: + txt.strike() +
) document.write(
Fontcolor: + txt.fontcolor(Red) +
) document.write(
Fontsize: + txt.fontsize(16) +
) document.write(
Link: + txt.link(http://www.w3school.com.cn) +
) function alertBig(){ alert(txt.big()); } </script>(三)indexOf方法:定位字串中某一個指定的字元首次出現的位置<script> var hw_text = Hello world; document.write(hw_text.indexOf(Hello)+
); document.write(hw_text.indexOf(world)+
); document.write(hw_text.indexOf(abc)+
); </script>(四)replace()方法:替換字串中的部分內容<script> var str=Visit Microsoft! document.write(str.replace(/Microsoft/,W3School)) </script>