方法 | 說明 | 範例 |
---|---|---|
length |
回傳字串長度 | "Hello".length → 5 |
charAt(index) |
回傳指定位置的字元 | "Hello".charAt(1) → "e" |
charCodeAt(index) |
回傳指定字元的 Unicode 編碼 | "A".charCodeAt(0) → 65 |
at(index) |
新的取字元方法(可用負數) | "Hello".at(-1) → "o" |
slice(start, end) |
擷取字串的一部分 | "Hello".slice(1, 4) → "ell" |
substring(start, end) |
擷取字串(不接受負數) | "Hello".substring(1, 4) → "ell" |
substr(start, length) |
擷取字串(已被棄用) | "Hello".substr(1, 3) → "ell" |
toUpperCase() |
轉為大寫 | "hello".toUpperCase() → "HELLO" |
toLowerCase() |
轉為小寫 | "HELLO".toLowerCase() → "hello" |
concat(str) |
連接字串 | "Hello".concat(" World") → "Hello World" |
trim() |
移除字串前後的空白 | " Hi ".trim() → "Hi" |
trimStart() / trimEnd() |
移除開頭或結尾空白 | " Hi ".trimStart() → "Hi " |
repeat(n) |
重複字串 n 次 | "Ha".repeat(3) → "HaHaHa" |
replace(old, new) |
取代第一個符合的字串 | "apple".replace("a", "A") → "Apple" |
replaceAll(old, new) |
取代所有符合的字串 | "aaa".replaceAll("a", "b") → "bbb" |
split(separator) |
分割字串成陣列 | "a,b,c".split(",") → ["a", "b", "c"] |
includes(str) |
是否包含指定字串 | "Hello".includes("ell") → true |
startsWith(str) |
是否以指定字串開頭 | "Hello".startsWith("He") → true |
endsWith(str) |
是否以指定字串結尾 | "Hello".endsWith("lo") → true |
indexOf(str) |
回傳第一次出現的位置 | "Hello".indexOf("l") → 2 |
lastIndexOf(str) |
回傳最後一次出現的位置 | "Hello".lastIndexOf("l") → 3 |
match(regex) |
使用正則表達式尋找符合的結果 | "abc123".match(/\d+/) → ["123"] |
search(regex) |
搜尋符合正則的索引 | "abc123".search(/\d+/) → 3 |
padStart(length, str) |
在開頭補上指定字元 | "5".padStart(3, "0") → "005" |
padEnd(length, str) |
在結尾補上指定字元 | "5".padEnd(3, "0") → "500" |
// 1️⃣ 基本操作
let text = "Hello World";
console.log(text.length); // 11
console.log(text.charAt(0)); // "H"
console.log(text.at(-1)); // "d"
// 2️⃣ 擷取字串
console.log(text.slice(0, 5)); // "Hello"
console.log(text.substring(6)); // "World"
// 3️⃣ 轉大小寫
console.log(text.toUpperCase()); // "HELLO WORLD"
console.log(text.toLowerCase()); // "hello world"
// 4️⃣ 搜尋與取代
console.log(text.includes("World")); // true
console.log(text.replace("World", "JS")); // "Hello JS"
// 5️⃣ 分割與合併
let parts = text.split(" ");
console.log(parts); // ["Hello", "World"]
console.log(parts.join("-")); // "Hello-World"
// 6️⃣ 補字與重複
console.log("5".padStart(3, "0")); // "005"
console.log("Hi".repeat(3)); // "HiHiHi"
1.字串是不可變的(immutable)
意味著你不能直接改變字串內容,只能建立新的字串:
let s = "abc";
s[0] = "A"; // 無效!
s = "A" + s.slice(1); // 正確的做法
2.處理大小寫時要小心語系差異
"ß".toUpperCase(); // "SS"(德文特例)