字串是日常開發裡最常被操作的型別,把常用方法攏在一支程式裡跑一遍,效果一目了然。以下範例以 var a = "abcDEfGgdefg32asdf38" 為受測字串。
var a = "abcDEfGgdefg32asdf38";
document.write("原始:" + a + "<br />")
document.write("粗體:" + a.bold() + "<br />");
document.write("大號:" + a.big() + "<br />");
document.write("斜體:" + a.italics() + "<br />");
document.write("刪除線:" + a.strike() + "<br />");
document.write("字體大小:" + a.fontsize(10) + "<br />");
document.write("字體顏色:" + a.fontcolor("#ff0000") + "<br />");
document.write("上標:" + a.sup() + "<br />");
document.write("下標:" + a.sub() + "<br />");
document.write("大寫:" + a.toUpperCase() + "<br />");
document.write("小寫:" + a.toLowerCase() + "<br />");
document.write("指定索引的字元:" + a.charAt(3) + "<br />"); // 得到 "D"
document.write("回傳索引:" + a.indexOf("f") + "<br />"); // 得到 5
document.write("逆向查找索引:" + a.lastIndexOf("f") + "<br />"); // 得到 9
document.write("搜尋字串:" + a.search("f") + "<br />"); // 得到 5,與 indexOf 相同
document.write("替換字串:" + a.replace("a", "A") + "<br />"); // 把 a 換成 A
document.write("擷取子字串:" + a.slice(1, 3) + "<br />"); // "bc",取索引 1 到 3-1
document.write("分割字串:" + a.split("D").toString() + "<br />"); // 以 D 為分隔符,回傳陣列
document.write("擷取子字串:" + a.substr(1, 2) + "<br />"); // 從索引 1 起、長度 2,即 "bc"
document.write("擷取子字串:" + a.substring(1, 3) + "<br />"); // 與 slice 同,取索引 1 到 3-1
document.write("比對:" + a.match(/\d+/) + "<br />"); // 正則比對,結果為 32
bold()、big()、fontsize()、fontcolor() 這類方法回傳的是包上一層 HTML 標籤的字串,屬於早期的呈現型 API,現代專案多半改用 CSS 處理樣式,知道有這回事即可。
擷取子字串的三兄弟要分清楚:slice(start, end) 與 substring(start, end) 的第二參數都是「結束索引(不含)」,差別在負值處理;而 substr(start, length) 的第二參數是長度,別混用。
至於查找,indexOf 與 lastIndexOf 回傳索引位置,找不到時回 -1;search 只接受正則表達式,回傳位置;match 則回傳比對結果本身。