型別的定義看過一次就懂,真正需要花時間的是各型別附帶的方法。本文用大量可執行的例子,把 Number 與 String 的常用方法整理清楚。
先提醒一個易混淆點:Boolean 物件與 boolean 基本型別是兩回事,建議永遠不要使用 Boolean 物件。
var num = 10; alert(num.toString()); // "10" alert(num.toString(2)); // "1010" alert(num.toString(8)); // "12" alert(num.toString(10)); // "10" alert(num.toString(16)); // "a"
var num = 10; num.toFixed(2); // "10.00"
var num = 10; alert(num.toExponential(1)); // "1.0e+1"
參數代表這個數字「總共要顯示幾位有效數字」(不含指數部分)。它會依情況自動選用定点或指數格式。
var num = 99; alert(num.toPrecision(1)); // "1e+2" —— 1 位有效數字無法表達 99,無條件進位成 100 alert(num.toPrecision(2)); // "99" alert(num.toPrecision(3)); // "99.0"
String 物件的方法,同樣可以在基本字串上直接呼叫。
兩者都接受一個從 0 開始的位置索引,前者回傳該位置的字符,後者回傳字符編碼。
var stringValue = "Hello world!"; stringValue.charAt(1); // "e" stringValue.charCodeAt(1); // 101
var str1 = "hello";
alert(str1.concat(" word")); // hello word
alert(str1.concat(" word", "!")); // hello word!
var stringValue = "Hello world!"; alert(stringValue.slice(3)); // lo world alert(stringValue.substring(3)); // lo world alert(stringValue.substr(3)); // lo world alert(stringValue.slice(3, 7)); // lo w —— 第二參數是結束位置 alert(stringValue.substring(3, 7)); // lo w —— 同上 alert(stringValue.substr(3, 7)); // lo worl —— 第二參數是長度
差異整理:slice 與 substring 的第二個參數是結束位置,substr 的第二個參數是長度。負數處理也不同——slice 支援負索引(從尾端往前數),substring 則會把負數當 0 處理。
兩者都搜尋子字串並回傳位置,找不到回傳 -1。差別只在搜尋方向。
var stringValue = "hello word";
alert(stringValue.indexOf("o")); // 4 —— 從頭往後找
alert(stringValue.lastIndexOf("o")); // 7 —— 從尾往前找
迴圈搭配可找出所有出現位置:
var stringValue = "wo de wei lai bu shi meng! wo men you geng hao de ming tian!";
var positions = [];
var pos = stringValue.indexOf("e");
while (pos > -1) {
positions.push(pos);
pos = stringValue.indexOf("e", pos + 1); // 從下一個位置繼續找
}
注意 pos + 1 這個細節:少了它,每次都會停在同一個位置而形成無限迴圈。
會回傳一個新字串,原字串不受影響。
var stringValue = " hello word "; alert(stringValue.trim()); // "hello word"
var stringValue = "hello word"; alert(stringValue.toLocaleUpperCase()); // 較穩妥,會遵循地區規則 alert(stringValue.toUpperCase()); alert(stringValue.toLocaleLowerCase()); // 較穩妥 alert(stringValue.toLowerCase());
第一個參數可以是字串或正則表達式,第二個參數可以是字串或函式。
var text = "cat,bat,sat,fat";
alert(text.replace("at", "ond")); // cond,bat,sat,fat —— 只換第一個
alert(text.replace(/at/g, "ond")); // cond,bond,sond,fond —— g 旗標全換
// 用捕獲群組做重排
alert(text.replace(/(.at)/g, "word ($1)"));
第二參數為函式時,可做更複雜的處理,例如 HTML 轉義:
function htmlEscape(text) {
// 函式會收到三個參數:匹配項、匹配位置、原始字串
return text.replace(/[<>"&]/g, function(match, index, text) {
switch (match) {
case "<": return "<";
case ">": return ">";
case "&": return "&";
case "\"": return """;
}
});
}
alert(htmlEscape("<p class=\"greeting\">Hello World!</p>"));
var stringValue = "f";
alert(stringValue.localeCompare("d")); // 1 —— 排在後面
alert(stringValue.localeCompare("f")); // 0 —— 相等
alert(stringValue.localeCompare("z")); // -1 —— 排在前面
它是 charCodeAt 的逆向操作。
alert(String.fromCharCode(104, 101, 108, 108, 111)); // "hello"
最後要提醒的是:字串在 JavaScript 中是不可變的。所有這些方法都不會改動原字串,而是回傳新字串。因此 str.trim() 若沒有把結果指派回去,等於什麼都沒做——這是初學者最常踩的坑。
另外,ES6 之後新增了 startsWith、endsWith、includes、padStart、repeat 等方法,以及模板字面值(template literals)。能用新語法表達的需求,就別再繞路用老方法拼接了。