字串是日常開發中操作頻率最高的型別之一。這裡把 JavaScript 字串的建立、存取、查找、截取、轉換與正則比對整理成一份可查的清單。
字串物件的方法同樣可以在原始值上呼叫,這是 JavaScript 自動包裝的結果。
var str = new String();
var str = new String('hello world'); // str.length = 11
charAt() / 索引取值:傳入位置,回傳該位置的字元。
var strValue = new String('hello world');
console.log(strValue.charAt(1)); // e
console.log(strValue[1]); // e(IE7 及以下會回傳 undefined)
charCodeAt():回傳該位置字元的編碼。
console.log(strValue.charCodeAt(1)); // 101
indexOf():第一個參數是要找的子字串,第二個可指定起點,找不到回傳 -1。
var str = 'hello world';
str.indexOf('l'); // 2
str.indexOf('l', 6); // 9
lastIndexOf():行為相同,但從尾端往前搜尋。
接受任意數量參數,回傳拼接後的新字串,原字串不變。
var str = new String('hello');
var result = str.concat(' world');
console.log(result); // hello world
typeof result; // "string"
三者都回傳子字串,且都不修改原字串,但負值的處理方式截然不同,這是面試與 bug 的熱點。
var str = 'hello'; // slice:支援負數索引,由後往前數 str.slice(0, 2); // "he" str.slice(-3); // "llo" str.slice(-2, -1); // "l" // substring:負數一律當 0 處理 str.substring(0, 2); // "he" str.substring(-3); // "hello" str.substring(-3, -2);// "" // substr:第二個參數是「長度」而非結束位置 str.substr(1, 2); // "el" str.substr(-3); // "llo" str.substr(-3, -1); // ""
補充:substr() 傳負數時舊版 IE 會回傳整個原字串,IE9 才修正。由於 substr 已被標記為 legacy,新專案建議統一用 slice 或 substring。
var color = 'blue,red,orange';
color.split(); // 長度 1
color.split(','); // ["blue", "red", "orange"]
'blue-red-orange'.split('-'); // ["blue", "red", "orange"]
color.split(',', 2); // ["blue", "red"]
var str = 'hello'; str.toUpperCase(); // "HELLO" str.toLowerCase(); // "hello" ' hello world '.trim(); // "hello world"
trim() 只移除前後空白,中間的不動。
match() 回傳比對結果陣列,第一項是整體匹配,後續為各捕獲組,並帶有 input 與 index 屬性:
var text = 'cat, bat, sat, fat'; var matches = text.match(/.at/); matches; // ["cat"] matches.input; // "cat, bat, sat, fat" matches.index; // 0
search() 回傳第一個匹配位置的索引,找不到回 -1,且永遠由前往後找:
'cat, bat, sat, fat'.search(/at/); // 1
replace() 是最需要小心的一個。若第一個參數是字串,只會替換第一個符合項;要全部替換務必用正則並加上 g 旗標。
var text = 'xxx-love-xxx';
text.replace(/xxx/g, '2'); // "2-love-2"
text.replace(/(xxx)-\w{4}-(xxx)/g, 'I love YOU'); // "I love YOU"
text.replace(/xxx/g, '$$'); // "$-love-$"
text.replace(/xxx/g, '$&2'); // "xxx2-love-xxx2"
第二個參數除了字串,也可以傳函式,參數依序為:整體匹配、各捕獲組、匹配位置、原始字串。需要在替換內容裡做運算時非常好用。
常用的特殊序列:
$$:插入 $ 符號$&:插入整個匹配的子字串$`:插入匹配位置之前的內容$':插入匹配位置之後的內容$n / $nn:插入第 n 個捕獲組