← JavaScript Learning Path

JAVASCRIPT V2 · EVERYDAY · 57

String / Number:Raw Input 進來後,先建立 Normalization Boundary

表單、URL、CSV、storage、API 欄位都可能帶著空白、大小寫差異或「看起來像數字的字串」。這一課不是背 method 清單,而是建立一個固定資料流程:raw input → normalize → validate → domain value → presentation。

Learning outcomes

1. Why now:Foundation 會算,但真實資料通常不乾淨

const rawName = "  Amy  ";
const rawScore = "90";

如果直接把 raw input 丟進 business logic,你會把 UI/transport 的資料格式問題混進 domain logic。比較穩定的流程是:

rawnormalizetyped valuevalidatedomain dataformatdisplay

2. String normalization:先消除無意義差異

const normalizedName =
  rawName.trim();

const query =
  rawQuery.trim().toLowerCase();

trim() 移除頭尾空白;case normalization 常用於搜尋比較,但不代表原始資料一定要全部改成小寫保存。

const matches =
  title.toLowerCase()
    .includes(query);

3. 文字處理不是只有 trim()

const text = "JavaScript,90,pass";

text.split(",");
text.slice(0, 10);
text.replace("pass", "PASS");
text.startsWith("Java");
text.endsWith("pass");

這些 method 解決的是「文字結構」問題。當資料開始有很多欄位、escaping、nested structure,就不應繼續靠手工 split 堆成 parser;那時要換更適合的 representation。

4. Worked Example A:搜尋 boundary 的 normalization

function matchesTitle(title, rawQuery) {
  const query =
    rawQuery.trim().toLowerCase();

  return title
    .toLowerCase()
    .includes(query);
}

這裡沒有改掉原本 title;normalization 只發生在 comparison boundary。

5. Numeric conversion:讓資料 contract 明確

const raw = "42";

const value = Number(raw);

console.log(value);        // 42
console.log(typeof value); // number
API例子契約直覺
Number(x)Number("42")整個 input 要能成為 number
parseInt(x,10)parseInt("42px",10)從開頭解析整數
parseFloat(x)parseFloat("3.14kg")從開頭解析浮點數

如果欄位 contract 是「純數字」,Number("42px") → NaN 反而比默默解析 42 更能暴露錯誤資料。

6. Worked Example B:空字串是特別危險的邊界

Number("")      // 0
Number("   ")   // 0

這代表「conversion 成功」不一定等於「使用者真的輸入了一個有效數字」。因此 normalization 與 validation 必須分開:

function normalizeScore(raw) {
  const text = raw.trim();

  if (text === "") {
    return null;
  }

  const value = Number(text);

  return Number.isNaN(value)
    ? null
    : value;
}

7. NaN 與有效 number 是不同概念

const value = Number("abc");

typeof value;               // "number"
Number.isNaN(value);        // true
Number.isFinite(value);     // false

typeof 只能告訴你 JavaScript type;domain 是否接受這個 numeric result,還要有額外規則。

8. Formatting 是 Presentation,不是 Calculation

const average = 87.456;
const display = average.toFixed(1);

console.log(display);        // "87.5"
console.log(typeof display); // "string"

內部計算盡量保留 number;真正要顯示時再 format。這能避免「格式化後的字串又被拿回去算」的混亂。

9. Worked Example C:完整 normalize + validate pipeline

function parseScore(raw) {
  const text = raw.trim();
  if (text === "") return null;

  const value = Number(text);

  if (
    Number.isNaN(value)
    || value < 0
    || value > 100
  ) {
    return null;
  }

  return value;
}
" 90 "trim"90"Number90range check90

10. Common mistakes

A. 覺得 trim() 會變 number

它仍然回 string。

B. 一律用 parseInt 因為「比較容易成功」

寬鬆解析可能把不合法資料誤當合法。

C. 只檢查 typeof value === "number"

NaN 也會通過。

D. 太早 toFixed()

formatting 回 string,可能污染後續 calculation。

11. Debug evidence:把 boundary 前後都印出來

console.log({
  raw,
  rawType: typeof raw,
  normalized,
  value,
  valueType: typeof value,
  isNaN: Number.isNaN(value)
});

這比只看畫面上「結果不對」更快定位是 cleaning、conversion 還是 validation 失敗。

12. Guided exercise:哪一步改變 type?

let x = " 12.5 ";
x = x.trim();
x = Number(x);
x = x.toFixed(1);

逐行寫出 value 與 type。特別注意最後一步。

13. Independent exercise:實作 normalizeScore(raw)

規則:trim 後空字串、非數字、超出 0–100 都回 "invalid";合法則回 number。至少測:

" 42 " → 42
""     → invalid
"abc"  → invalid
"101"  → invalid
"0"    → 0
"100"  → 100

14. Challenge:搜尋與保存應該用同一種 normalization 嗎?

名字顯示要保留原大小寫,但搜尋可使用 lower-case comparison。思考哪些 normalization 是 presentation-only、哪些是 domain canonicalization。

Project checkpoint:Grade Tracker Input Boundary

function normalizeStudentInput(
  rawName,
  rawScore
) {
  const name = rawName.trim();
  const score = normalizeScore(rawScore);

  if (!name || score === "invalid") {
    throw new Error("Invalid student input");
  }

  return { name, score };
}

從這一刻起,Grade Tracker 的 business logic 可以假設 score 已經是合法 number,不需要每個 function 都重新猜型別。

15. Vocabulary / Summary

16. Further reading

Knowledge check

  1. 說明 normalization、conversion、validation、formatting 的差異。
  2. 比較 Number("42px") 與 parseInt("42px",10)。
  3. 說明為什麼 Number("") 是危險邊界。
  4. 解釋 toFixed() 為什麼通常放在 presentation boundary。
  5. 完成 mastery exercise 並讓 invalid/boundary tests 全 PASS。