DIV CSS 佈局教程網

JavaScript 資料型別實戰:Number 與 String 常用方法逐項拆解
編輯:關於JavaScript     

型別的定義看過一次就懂,真正需要花時間的是各型別附帶的方法。本文用大量可執行的例子,把 Number 與 String 的常用方法整理清楚。

一、Number 物件的格式化方法

先提醒一個易混淆點:Boolean 物件與 boolean 基本型別是兩回事,建議永遠不要使用 Boolean 物件。

toString(基数):進位轉換

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"

toFixed(n):指定小數位數

var num = 10;
num.toFixed(2);   // "10.00"

toExponential(n):科學記號

var num = 10;
alert(num.toExponential(1));   // "1.0e+1"

toPrecision(n):自動選最佳格式

參數代表這個數字「總共要顯示幾位有效數字」(不含指數部分)。它會依情況自動選用定点或指數格式。

var num = 99;
alert(num.toPrecision(1));   // "1e+2" —— 1 位有效數字無法表達 99,無條件進位成 100
alert(num.toPrecision(2));   // "99"
alert(num.toPrecision(3));   // "99.0"

二、String 的字符操作

String 物件的方法,同樣可以在基本字串上直接呼叫。

charAt() 與 charCodeAt()

兩者都接受一個從 0 開始的位置索引,前者回傳該位置的字符,後者回傳字符編碼。

var stringValue = "Hello world!";
stringValue.charAt(1);      // "e"
stringValue.charCodeAt(1);  // 101

concat():拼接

var str1 = "hello";
alert(str1.concat(" word"));        // hello word
alert(str1.concat(" word", "!"));   // hello word!

slice / substring / substr:三者最容易搞混

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 處理。

indexOf() 與 lastIndexOf()

兩者都搜尋子字串並回傳位置,找不到回傳 -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 這個細節:少了它,每次都會停在同一個位置而形成無限迴圈。

trim():去除前後空白

會回傳一個新字串,原字串不受影響。

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());

replace():字串替換

第一個參數可以是字串或正則表達式,第二個參數可以是字串或函式。

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 "&lt;";
      case ">":  return "&gt;";
      case "&":  return "&amp;";
      case "\"": return "&quot;";
    }
  });
}
alert(htmlEscape("<p class=\"greeting\">Hello World!</p>"));

localeCompare():字串比較

var stringValue = "f";
alert(stringValue.localeCompare("d"));   // 1  —— 排在後面
alert(stringValue.localeCompare("f"));   // 0  —— 相等
alert(stringValue.localeCompare("z"));   // -1 —— 排在前面

String.fromCharCode():由編碼組字串

它是 charCodeAt 的逆向操作。

alert(String.fromCharCode(104, 101, 108, 108, 111));   // "hello"

三、使用建議

最後要提醒的是:字串在 JavaScript 中是不可變的。所有這些方法都不會改動原字串,而是回傳新字串。因此 str.trim() 若沒有把結果指派回去,等於什麼都沒做——這是初學者最常踩的坑。

另外,ES6 之後新增了 startsWith、endsWith、includes、padStart、repeat 等方法,以及模板字面值(template literals)。能用新語法表達的需求,就別再繞路用老方法拼接了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved