在 JavaScript 中,字串(String) 是一種用來儲存文字資料的資料型別。
字串可以包含文字、數字或符號,並以 單引號 ('')、雙引號 ("") 或 反引號 (``) 括起來。
let str1 = "Hello World";
let str2 = 'JavaScript';
let str3 = `String Example`;
let text = "Hello";          // 字面值
let text2 = new String("Hi"); // String 物件
new String() 會建立物件,不建議使用,除非你需要字串物件的特殊行為。
| 屬性 | 說明 | 範例 | 
|---|---|---|
length | 
回傳字串的長度 | "Hello".length // 5 | 
let text = "JavaScript";
console.log(text.length); // 10
取得特定字元
let text = "Hello";
console.log(text.charAt(1));     // e
console.log(text.charCodeAt(1)); // 101
console.log(text[1]);            // e
| 方法 | 說明 | 範例 | 
|---|---|---|
indexOf() | 
回傳第一次出現的位置 | "Hello".indexOf("l") // 2 | 
lastIndexOf() | 
回傳最後一次出現的位置 | "Hello".lastIndexOf("l") // 3 | 
includes() | 
檢查是否包含指定字串 | "Hello".includes("e") // true | 
startsWith() | 
是否以指定字串開頭 | "Hello".startsWith("He") // true | 
endsWith() | 
是否以指定字串結尾 | "Hello".endsWith("lo") // true | 
| 方法 | 說明 | 範例 | 
|---|---|---|
slice(start, end) | 
擷取部分字串(不含 end) | "Hello".slice(1, 4) // ell | 
substring(start, end) | 
類似 slice,但不接受負數 | "Hello".substring(1, 4) // ell | 
substr(start, length) | 
從 start 取出指定長度 | "Hello".substr(1, 3) // ell | 
let text = "JavaScript";
console.log(text.toUpperCase()); // JAVASCRIPT
console.log(text.toLowerCase()); // javascript
let a = "Hello";
let b = "World";
console.log(a.concat(" ", b)); // Hello World
let message = a + " " + b; // Hello World
let text = "   Hello World!   ";
console.log(text.trim());      // "Hello World!"
console.log(text.trimStart()); // "Hello World!   "
console.log(text.trimEnd());   // "   Hello World!"
let text = "I love cats";
console.log(text.replace("cats", "dogs")); // I love dogs
let text = "apple apple apple";
console.log(text.replaceAll("apple", "banana")); // banana banana banana
let text = "a,b,c,d";
let arr = text.split(",");   // ["a","b","c","d"]
let newText = arr.join("-"); // a-b-c-d
console.log("Hi".repeat(3));      // HiHiHi
console.log("5".padStart(3, "0")); // 005
console.log("5".padEnd(3, "0"));   // 500
使用 反引號(`) 可以插入變數或換行:
let name = "Tom";
let age = 25;
let message = `Hello ${name}, you are ${age} years old.`;
console.log(message);
let poem = `
Roses are red,
Violets are blue.
`;
| 方法 | 說明 | 
|---|---|
toString() | 
轉成字串 | 
valueOf() | 
回傳原始字串值 | 
match() | 
比對正則表達式 | 
search() | 
搜尋正則表達式 | 
replace() | 
替換字串 | 
localeCompare() | 
比較字串順序 | 
normalize() | 
Unicode 標準化 | 
fromCharCode() | 
根據 Unicode 產生字元(靜態方法) | 
字串在 JavaScript 中是 不可變(immutable) 的。
所有字串方法都會 回傳新字串,不會改變原始字串。
反引號(``)可讓你更靈活地嵌入變數與換行。