Javascript中的String對象詳談

來源:互聯網
上載者:User

Sting字串對象是Javascript提供的內建對象之一。

這裡特別注意,字串中的第一個字元是第0位的,第二個才是第1位的。

1.建立一個字串對象的方法

[var] String 對象執行個體名 = new String(string)

或者是var String 對象執行個體名 = 字串值

例子:

var str = "Hello World";

var str1 = new String("This is a string");

2.String的屬性

length: 返回字串的長度

var intlength = str.length //intlength = 11

3.String的方法

charAt(*): 返回字串位於第*位的單個字元

var x = "abcdefg"; var y = x.charAt(3); //y="d"

charCodeAt(*): 返回字串位於第*位的單個字元的ASCII碼

不作贅述
複製代碼 代碼如下:
fromCharCode(): 接受一個指定的Unicode值,然後返回一個字串。

document.write(String.fromCharCode(72,69,76,76,79)); //輸出結果是HELLO

indexOf():從字串中尋找另一個字串對象,尋找成功返回位置,否則返回-1

document.write("children".indexOf("l",0)); //輸出結果是3

document.write("children".indexOf("l",1)); //輸出結果是3

document.write("children".indexOf("l",4)); //輸出結果是-1

lastIndexOf():和indexOf()方法類似,不同的是尋找方向相反,從後往前尋找

document.write("children".lastIndexOf("l",4)); //輸出結果是3

split(分隔字元字元): 返回一個數組,數組是從字串中分離出來的,分隔字元字元決定了分離的地方。

'l&o&v&e'.split('&'); //返回數組l,o,v,e

substring(): 相當於字串的裁剪功能

substring(<始>[,<終>])

document.write("children".substring(1,3)); //輸出結果是hil

substr():也相當於裁剪,注意與substring()的不同

substr(<始>[,<長度>])
複製代碼 代碼如下:
document.write("children".substr(1,3)); //輸出結果是hil。這裡要注意與substing相比較,雖然結果是一樣的,但是演算法和思想都是不一樣的。

toLowerCase()和toUpperCase():功能類似,只是返回一個原來字串相同的字串,唯一的區別就是前者所有的字母都為小寫,後者為大寫。

document.write("LOVE".toLowerCase()); //輸出結果是love

document.write("love".toUpperCase()); //輸出結果是LOVE

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.