String類型的主要函數
/* 字符串連接用 + 運算符 */
alert( "Wasabi "+"你好嗎?"); //outputs "Wasabi 你好嗎?"
/* 字符串查找function indexOf() , lastIndexOf() */
var sHello = "hello world";
alert( sHello.indexOf('o')); //outputs 4
alert( sHello.lastIndexOf('o')); //outputs 7
/* 如果找不到會返回 -1 */
alert( sHello.indexOf('Z') == -1 ); //outputs true
/* 字符串比較function localeCompare() */
var str = "yellow";
alert( str.localeCompare("brick") ); //outputs 1
alert( str.localeCompare("yellow") ); //outputs 0
alert( str.localeCompare("zoo") ); //outputs -1
/* 訪問字符串中的單個字符function charAt(), charCodeAt() */
var str = "hello world";
alert( str.charAt(1) ); //outputs 'e'
//想要得到該字符的ASCII編碼用 charCodeAt()
alert( str.charCodeAt(1) ); //outputs '101'
/* 提取字符串function slice(),substring() */
/* 這兩種方法返回的都是要處理的字符串的子串,都接受一個或兩個參數。 第一個參數是要獲取的子串的起始位置,第二個參數是要獲取終止前的位置,如果省略第二個參數,終止位就默認為字符串的長度。 兩個方法都不會改變String對象自身的值。 */
var str = "hello world";
alert( str.slice(3) ); //outputs "lo world"
alert( str.substring(3) ); //outputs "lo world"
alert( str.slice(3,7) ); //outputs "lo w"
alert( str.substring(3,7) ); //outputs "lo w"
/* 隻有參數為負數時,這兩個方法得到的結果才有不同,對於負參數,slice()方法會用字符串的長度加上參數,substring()方法則將其作為0處理(即忽略它)。 */
alert( str.slice(-3) ); //outputs "rld"
alert( str.substring(-3) ); //outputs "hello world"
alert( str.slice(3,-4) ); //outputs "lo w"
/* 實際上substring()方法總是把較小的數字作為數字的起始位,較大的數字作為終止位,因此substring(3,-4) 返回"hel" */
alert( str.substring(3,-4) ); //outputs "hel"
/* 字符串大小寫轉換,有4種方法用於執行大小寫轉換 , 一般來說,如果不知道在以哪種編碼運行一種語言,則使用區域特定的方法比較安全*/
var str = "hello world";
alert( str.toLocaleUpperCase() ); //outputs "HELLO WORLD"
alert( str.toUpperCase() ); //outputs "HELLO WORLD"
alert( str.toLocaleLowerCase() ); //outputs "hello world"
alert( str.toLowerCase() ); //outputs "hello world"