Skip to content

JavaScript 字符串方法

JavaScript 字符串是不可变的(immutable),这意味着一旦创建,其内容就无法改变。字符串方法作用于一个字符串并返回一个新字符串或不同的值,而不会修改原始字符串。本节介绍一些最常用且有用的字符串方法。

查找子字符串:indexOf()、lastIndexOf()、includes()、startsWith()、endsWith()

Section titled “查找子字符串:indexOf()、lastIndexOf()、includes()、startsWith()、endsWith()”

Returns the index of the first occurrence of searchValue within the string. If not found, returns -1. fromIndex is an optional starting position for the search.

const text = "Hello world, welcome to the world!";
console.log(text.indexOf("world")); // 输出: 6
console.log(text.indexOf("world", 10)); // 输出: 29 (从索引 10 开始搜索)
console.log(text.indexOf("galaxy")); // 输出: -1

Similar to indexOf(), but returns the index of the last occurrence, searching backwards from fromIndex (or end of string if fromIndex is omitted).

console.log(text.lastIndexOf("world")); // 输出: 29

Checks if a string contains searchValue. Returns true or false. More readable for simple presence checks.

console.log(text.includes("welcome")); // 输出: true
console.log(text.includes("galaxy")); // 输出: false

Checks if a string starts with searchValue. position is an optional starting position. Returns true or false.

console.log(text.startsWith("Hello")); // 输出: true
console.log(text.startsWith("world", 6)); // 输出: true (检查从索引 6 开始的子字符串是否以 "world" 开头)

Checks if a string ends with searchValue. length is an optional length of the string to consider. Returns true or false.

console.log(text.endsWith("world!")); // 输出: true
console.log(text.endsWith("welcome", 20)); // 输出: true (考虑前 20 个字符: "Hello world, welcome")

提取字符串部分:slice()、substring()、substr()(遗留/旧式)

Section titled “提取字符串部分:slice()、substring()、substr()(遗留/旧式)”

Extracts a section of a string and returns it as a new string. startIndex is inclusive, endIndex is exclusive. Negative indices count from the end of the string.

const fruitStr = "Apple, Banana, Kiwi";
console.log(fruitStr.slice(7, 13)); // 输出: "Banana"
console.log(fruitStr.slice(7)); // 输出: "Banana, Kiwi" (到末尾)
console.log(fruitStr.slice(-4)); // 输出: "Kiwi" (最后 4 个字符)
console.log(fruitStr.slice(-12, -6)); // 输出: "Banana"

Similar to slice(), but if startIndex is greater than endIndex, they are swapped. Negative indices are treated as 0.

console.log(fruitStr.substring(7, 13)); // 输出: "Banana"
console.log(fruitStr.substring(13, 7)); // 输出: "Banana" (索引已交换)
console.log(fruitStr.substring(-5, 13)); // 输出: "Apple, Banana" (负数索引被视为 0)

substr(startIndex[, length]) - Legacy/Deprecated

Section titled “substr(startIndex[, length]) - Legacy/Deprecated”

Extracts a substring starting at startIndex with a specified length. Note: This method is considered a legacy feature in ECMAScript and its use is discouraged. slice() or substring() are preferred.

// console.log(fruitStr.substr(7, 6)); // 输出: "Banana" (请改用 slice 或 substring)

替换字符串内容:replace(), replaceAll()

Section titled “替换字符串内容:replace(), replaceAll()”

Returns a new string with some or all matches of searchValue replaced by replacementValue. If searchValue is a string, only the first occurrence is replaced. If searchValue is a regular expression with the global (g) flag, all occurrences are replaced.

const message = "Please visit Microsoft! Microsoft is great.";
console.log(message.replace("Microsoft", "W3Schools")); // 输出: "Please visit W3Schools! Microsoft is great."
console.log(message.replace(/Microsoft/g, "W3Schools")); // 输出: "Please visit W3Schools! W3Schools is great."

replaceAll(searchValue, replacementValue) (ES2021)

Section titled “replaceAll(searchValue, replacementValue) (ES2021)”

Returns a new string with all occurrences of searchValue replaced by replacementValue. searchValue can be a string or a non-global regular expression.

console.log(message.replaceAll("Microsoft", "Google")); // 输出: "Please visit Google! Google is great."

改变大小写:toUpperCase()、toLowerCase()

Section titled “改变大小写:toUpperCase()、toLowerCase()”

toUpperCase():将字符串转换为大写。

const greeting = "Hello World!";
console.log(greeting.toUpperCase()); // 输出: "HELLO WORLD!"

toLowerCase():将字符串转换为小写。

console.log(greeting.toLowerCase()); // 输出: "hello world!"

连接字符串:concat() 方法和 + 运算符 / 模板字面量

Section titled “连接字符串:concat() 方法和 + 运算符 / 模板字面量”

Joins two or more strings and returns a new string.

const str1 = "Hello";
const str2 = " ";
const str3 = "World";
console.log(str1.concat(str2, str3, "!")); // 输出: "Hello World!"

+ 运算符或模板字面量通常更常用,并且对于字符串连接而言通常更易读:

console.log(str1 + str2 + str3 + "!"); // 输出: "Hello World!"
console.log(`${str1}${str2}${str3}!`); // 输出: "Hello World!" (使用模板字面量)

去除空白字符:trim()、trimStart()、trimEnd()

Section titled “去除空白字符:trim()、trimStart()、trimEnd()”

trim():移除字符串两端的空白字符。

const paddedText = " Hello, World! ";
console.log(paddedText.trim()); // 输出: "Hello, World!"

trimStart() 或 trimLeft() (ES2019):移除字符串开头的空白字符。

console.log(paddedText.trimStart()); // 输出: "Hello, World! "

trimEnd() 或 trimRight() (ES2019):移除字符串末尾的空白字符。

console.log(paddedText.trimEnd()); // 输出: " Hello, World!"

填充字符串:padStart()、padEnd() (ES2017)

Section titled “填充字符串:padStart()、padEnd() (ES2017)”

Pads the current string from the start with a given string (repeatedly, if needed) until the resulting string reaches the targetLength. Default padString is a space.

const numStr = "5";
console.log(numStr.padStart(4, "0")); // 输出: "0005"
console.log("abc".padStart(5)); // 输出: " abc"

Pads the current string from the end.

console.log(numStr.padEnd(4, "*")); // 输出: "5***"
console.log("abc".padEnd(5, ".")); // 输出: "abc.."

提取字符串字符:charAt()、charCodeAt()、属性访问

Section titled “提取字符串字符:charAt()、charCodeAt()、属性访问”

Returns the character at a specified index in a string.

const myString = "HELLO";
console.log(myString.charAt(0)); // 输出: "H"

Returns the Unicode (UTF-16 code unit) of the character at a specified index.`

console.log(myString.charCodeAt(0)); // 输出: 72 ('H' 的 Unicode 值)

Strings can be treated like read-only arrays to access characters by index. This is now widely supported and generally safe for reading.

console.log(myString[1]); // 输出: "E"

注意:尝试对字符位置进行赋值(例如,myString[0] = "J";)不会改变字符串(因为字符串是不可变的),并且在非严格模式下不会导致错误(在严格模式下可能会因引擎而异)。

Splits a string into an array of substrings, using separator to determine where to make the splits. limit is an optional integer specifying the maximum number of splits.

const csvData = "apple,banana,cherry,date";
console.log(csvData.split(",")); // 输出: ["apple", "banana", "cherry", "date"]
console.log("Hello World".split(" ")); // 输出: ["Hello", "World"]
console.log("test".split("")); // 输出: ["t", "e", "s", "t"] (分割成单个字符)
// 如果省略或未找到分隔符,则返回一个只包含原始字符串作为唯一元素的数组。
console.log(" одиночный ".split()); // 输出: [" одиночный "]

This covers many common string methods. For a comprehensive list, descriptions, and examples of all string properties and methods, refer to the MDN Web Docs on String.