創建字符串:
1.使用字面量(推薦)
:
這是最常用、最直接的方式。你可以用單引號 ('
)、雙引號 ("
) 或反引號 (`
) 把文本包起來
let singleQuote = '單引號';
let doubleQuote = "雙引號";
let templateLiteral = `反引號`;
2.使用String 構造函數(不推薦)
這種方式會創建一個字符串對象 (Object),而不是一個基本類型的值,可能會在比較時產生意想不到的結果。
let strObject = new String("這是一個字符串對象");
console.log(typeof strObject); // "object"
let strLiteral = "這是一個字符串字面量";
console.log(typeof strLiteral); // "string"
字符串的不可變性:
一旦一個字符串被創建,它的內容就永遠無法被改變。
let greeting = "Hello";
greeting = greeting + ", World!"; // 拼接
console.log(greeting); // "Hello, World!"
表面上看,greeting
變量的值被改變了。但實際上,內存中發生的事情是:greeting + ", World!"
創建了一個全新的字符串 "Hello, World!"
。然后 greeting
變量的“指針”從舊的 "Hello"
指向了這個新的字符串。
字符串的屬性和方法:
charAt(index)
- 功能: 返回字符串中指定索引位置的單個字符。
- 參數:
index
(必需): 一個整數,表示你想要獲取的字符的索引 (從 0 開始)。 - 返回值: 一個只包含單個字符的新字符串。如果 index 超出范圍,返回一個空字符串 “”。
let str = "JavaScript";
// 獲取第一個字符
console.log(str.charAt(0)); // "J"
// 獲取第五個字符
console.log(str.charAt(4)); // "S"
// 如今更常用方括號 str[0] 的寫法,但它在索引越界時返回 undefined。
slice(startIndex, endIndex)
- 功能: 提取字符串的一個片段,并以新字符串的形式返回它,原始字符串不會被修改。
- 參數:
startIndex
(必需): 開始提取的索引。如果為負數,則從字符串尾部開始計算。 - endIndex (可選): 結束提取的索引 (該索引處的字符不被包含)。如果省略,則提取到字符串末尾。如果為負數,也從尾部計算。
- 返回值: 包含提取部分的新字符串。
let text = "The quick brown fox";
// 提取 "quick"
console.log(text.slice(4, 9)); // "quick"
// 從索引 10 到末尾
console.log(text.slice(10)); // "brown fox"
// 提取最后 3 個字符
console.log(text.slice(-3)); // "fox"
substring(startIndex, endIndex)
- 功能: 與 slice() 類似,提取字符串的片段并返回。
- 參數:startIndex (必需): 開始提取的索引。
- endIndex (可選): 結束提取的索引 (不包含)。
- 返回值: 包含提取部分的新字符串。
- 與 slice() 的核心區別:
- 不支持負數索引:任何負數參數都會被視為 0。
- 參數位置可互換:如果 startIndex 大于 endIndex,方法會自動交換這兩個參數。
let str = "Mozilla";
console.log(str.substring(1, 4)); // "ozi"
// 自動交換參數 4 和 1
console.log(str.substring(4, 1)); // "ozi"
// 負數被視為 0
console.log(str.substring(-2, 4)); // "Mozi" (相當于 substring(0, 4))
includes(searchValue, position)
- 功能: 判斷一個字符串是否包含另一個指定的子字符串。
- 參數: searchValue (必需): 要查找的子字符串。
- position (可選): 開始搜索的索引位置,默認為 0。
- 返回值: true (如果找到) 或 false (如果未找到)。
let sentence = "Hello, welcome to the universe.";
console.log(sentence.includes("welcome")); // true
console.log(sentence.includes("world")); // false
// 從索引 8 開始搜索 "welcome"
console.log(sentence.includes("welcome", 8)); // true
indexOf(searchValue, fromIndex)
- 功能:查找指定子字符串首次出現的索引。
- 參數:searchValue (必需): 要查找的子字符串。
- fromIndex (可選): 開始搜索的起始索引,默認為 0。
- 返回值: 第一個匹配項的索引。如果未找到,則返回 -1。
let paragraph = "The quick brown fox jumps over the lazy dog. If the dog barked, was it a quick dog?";
// 查找第一個 "dog"
console.log(paragraph.indexOf("dog")); // 40
// 從索引 41 之后開始查找 "dog"
console.log(paragraph.indexOf("dog", 41)); // 72
// 查找一個不存在的詞
console.log(paragraph.indexOf("cat")); // -1
lastIndexOf(searchValue, fromIndex)
- 功能: 與 indexOf() 類似,但它是從字符串的末尾向前搜索,返回最后一次出現的索引。
- 參數:searchValue (必需): 要查找的子字符串。
- fromIndex (可選): 從該索引處開始向前搜索。默認為字符串的長度。
- 返回值: 最后一個匹配項的索引,未找到則返回 -1
let paragraph = "The quick brown fox jumps over the lazy dog. If the dog barked, was it a quick dog?";
console.log(paragraph.lastIndexOf("dog")); // 72
startsWith(searchString, position)
- 功能: 判斷當前字符串是否以另一個給定的子字符串開頭。
- 參數:searchString (必需): 要搜索的子字符串。
- position (可選): 開始搜索的索引位置,默認為 0。
- 返回值: true 或 false。
let str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be")); // true
// 檢查從索引 14 開始的子串是否以 "that" 開頭
console.log(str.startsWith("that", 24)); // true
endsWith(searchString, length)
- 功能: 判斷當前字符串是否以另一個給定的子字符串結尾。
- 參數:searchString (必需): 要搜索的子字符串。
- length (可選): 指定要檢查的字符串的長度。默認為整個字符串的長度。
- 返回值: true 或 false。
let str = "Cats are the best!";
console.log(str.endsWith("best!")); // true
// 檢查前 8 個字符 "Cats are" 是否以 "are" 結尾
console.log(str.endsWith("are", 8)); // true
replace(searchValue, newValue)
- 功能: 用某些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
- 參數: searchValue (必需): 要被替換的字符串或正則表達式 (RegExp)。
- newValue (必需): 用于替換的字符串或函數。
- 返回值: 一個部分或全部匹配項被替換的新字符串。
let p = "The quick brown fox jumps over the lazy dog. If the dog barked, was it a quick dog?";
// 當 searchValue 是字符串時,只替換第一個匹配項
console.log(p.replace("dog", "monkey"));
// "The quick brown fox ... lazy monkey. If the dog barked..." // 使用帶 g (全局)標志的正則表達式,替換所有匹配項
console.log(p.replace(/dog/g, "cat"));
// "The quick brown fox ... lazy cat. If the cat barked..."
replaceAll(searchValue, newValue)
- 功能: 替換所有匹配的子串。
- 參數: searchValue (必需): 字符串或必須帶 g 標志的正則表達式。
- newValue (必需): 用于替換的字符串或函數。
- 返回值: 所有匹配項被替換的新字符串。
let str = "I like cats. My favorite cats are Siamese cats.";
// 使用字符串直接替換所有 "cats"
console.log(str.replaceAll("cats", "dogs")); // "I like dogs. My favorite dogs are Siamese dogs."
toLowerCase() 和 toUpperCase()
- 功能: 分別將字符串轉換為全小寫或全大寫。
- 參數: 無。
- 返回值: 轉換后的新字符串。
let text = "Hello World!";
console.log(text.toLowerCase()); // "hello world!"
console.log(text.toUpperCase()); // "HELLO WORLD!"
trim(), trimStart(), trimEnd()
- 功能: 移除字符串開頭、結尾或兩端的空白字符 (空格、制表符、換行符等)。
- 參數: 無。
- 返回值: 移除空白后的新字符串。
let greeting = " Hello there! ";
console.log(greeting.trim()); // "Hello there!"
console.log(greeting.trimStart()); // "Hello there! "
console.log(greeting.trimEnd()); // " Hello there!"
split(separator, limit)
- 功能: 使用指定的分隔符將一個字符串分割成一個字符串數組。
- 參數: separator (必需): 用作分割依據的字符串或正則表達式。如果為空字符串 “”,則每個字符都會被分割。
- limit (可選): 一個整數,限制返回的數組中的元素個數。
- 返回值: 一個包含分割后子串的數組。
let csv = "2025,August,17,Sunday";
let parts = csv.split(',');
console.log(parts); // ["2025", "August", "17", "Sunday"]
let word = "character";
console.log(word.split('')); // ["c", "h", "a", "r", "a", "c", "t", "e", "r"]
padStart(targetLength, padString) 和 padEnd(targetLength, padString)
- 功能: 在當前字符串的開頭 (padStart) 或結尾 (padEnd) 填充指定的字符串,直到達到目標長度。
- 參數:targetLength (必需): 最終生成的字符串的期望長度。
- padString (可選): 用來填充的字符串,默認為空格。
- 返回值: 填充后的新字符串。
let orderId = "123";
// 通常用于補全編號,如在開頭補 0
console.log(orderId.padStart(8, '0')); // "00000123" let label = "Chapter 1";
// 在結尾補點,用于對齊
console.log(label.padEnd(20, '.')); // "Chapter 1..........."
concat(…strings)
- 功能: 將一個或多個字符串與原字符串連接合并。
- 參數 …strings (必需): 一個或多個要連接的字符串。
- 返回值: 連接后的新字符串。
let str1 = "Hello";
let str2 = "World";
console.log(str1.concat(' ', str2, '!')); // "Hello World!"
// 注意:在現代 JS 中,加號 `+` 或模板字符串 `` `${}` `` 是更常用和更高效的拼接方式。
// let result = str1 + ' ' + str2 + '!';
// let result = `${str1} ${str2}!`;
repeat(count)
- 功能: 將字符串重復指定的次數。
- 參數: count (必需): 一個整數,表示重復的次數。
- 返回值: 包含重復內容的新字符串。
let cheer = "Go! ";
console.log(cheer.repeat(3)); // "Go! Go! Go! " let separatorLine = "=".repeat(20);
console.log(separatorLine); // "===================="