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的文檔進行查閱。
轉載請標明出處。。。。