Javascript:字串對象(string)的基本操作

來源:互聯網
上載者:User

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>



 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.