Javascript 基礎之String對象__Java

來源:互聯網
上載者:User
String 對象

建立String對象

var string1 = new String("hello");var string2 = new String(123);var string3 = new String(123.456);

也可以這樣:

var string4 = "hello";
String對象的屬性和方法

length屬性

length屬性返回字串中的字元數。
例如:

    var myName = new String ("Jeremy");    document.write(myName.length);

輸出:6

indexOf() 和 lastindexOf() ————在一個字串中尋找另一個字串

方法對大小寫敏感。

如果要檢索的字串值沒有出現,則該方法返回 -1。

indexOf() 和 lastindexOf()的參數中第一個為必選參數,為要檢索的字串,第二個參數為選擇性參數,indexOf預設為從首開始檢索,lastindexOf預設從string.length-1位置開始檢索

indexOf()

var str="Hello world!"document.write(str.indexOf("Hello") + "<br />")//輸出0document.write(str.indexOf("World") + "<br />")//輸出-1

lastindexOf()

var str="Hello world!"document.write(str.lastIndexOf("Hello") + "<br />")//輸出0document.write(str.lastIndexOf("World") + "<br />")//輸出-1

substr() 和 substring()方法————提取子串

substr() 方法可在字串中抽取從 start 下標開始的指定數目的字元。

var str="Hello world!"document.write(str.substr(3,7))//輸出 lo worl

substring() 方法用於提取字串中介於兩個指定下標之間的字元。該方法用起來就是包含頭不包含尾

var str="Hello world!"document.write(str.substring(3,7))//輸出 lo w 

toLowerCase() 和 toUpperCase() ————轉換大小寫

var txt="Hello World!"document.write(txt.toLowerCase());// hello world!document.write(xt.toUpperCase());// HELLO WORLD!

charAt() 和 charCodeAt() 方法————從字串中選取一個字元

方法 charCodeAt() 與 charAt() 方法執行的操作相似,只不過前者返回的是位於指定位置的字元的編碼,而後者返回的是字元子串。

var str=”Hello world!”
document.write(str.charAt(1));// e
document.write(str.charCodeAt(1));// 101

fromCharCode() 方法

fromCharCode() 可接受一個指定的 Unicode 值,然後返回一個字串。

document.write(String.fromCharCode(72,69,76,76,79));// HELLO document.write("<br />")document.write(String.fromCharCode(65,66,67));// ABC

String方法還有一些方法再次不再贅述,有興趣的可以參考W3C的文檔進行查閱。

轉載請標明出處。。。。

聯繫我們

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