JavaScript 字符串
创建, slicing, 搜索, and transforming 文本使用构建-in 字符串方法.
你将学到
- 创建字符串使用单个, 双, and backtick quotes
- 核心方法: 长度, slice, indexOf, replace, 拆分, trim
- 为什么字符串是 不可变 and 方法返回新 字符串
- 搜索使用包含, startsWith, endsWith, and localeCompare
- Converting 情况 and handling Unicode safely
概念讲解
What Is a String?
A string is an ordered sequence of characters used to represent text. In JavaScript, strings are a primitive type, which means they are immutable — once created, a string cannot be changed in place. Every method that appears to "修改" a string actually returns a brand-new string.
You can create strings with single quotes, double quotes, or backticks (template literals). Single and double quotes are interchangeable; backticks allow multiline text and interpolation.
Accessing Characters and Slicing
Strings are zero-indexed and have a 长度 property. You can read individual characters with bracket notation or charAt(), and extract substrings with slice(), substring(), or substr() (deprecated). slice() accepts negative indices to count from the end, making it the most flexible choice.
Searching and Testing
JavaScript provides a rich set of search methods: indexOf() returns the position of a substring (or -1), 包含() returns a boolean, and startsWith() / endsWith() check the boundaries. For pattern matching, match() and replace() work with regular expressions. When comparing strings for sorting, prefer localeCompare() over raw < / > so that accented characters and language-specific rules sort correctly.
Transformation Methods
Common transformations include toUpperCase(), toLowerCase(), trim() (remove surrounding whitespace), 拆分() (break into an array), replace() (swap text), and repeat() (duplicate the string). Because strings are immutable, remember to assign the result — calling str.trim() without capturing the return value does nothing to str.
示例代码
const sentence = " The quick brown fox ";
// trim removes leading/trailing whitespace — remember to capture the result
const clean = sentence.trim();
console.log(clean); // "The quick brown fox"
// slice with negative index counts from the end
const lastWord = clean.slice(-3);
console.log(lastWord); // "fox"
// split into words, then map to lengths
const words = clean.split(" ");
const lengths = words.map((w) => w.length);
console.log(lengths); // [3, 5, 5, 3]
// search and replace
const hasFox = clean.includes("fox");
const noFox = clean.replace("fox", "cat");
console.log(hasFox, noFox); // true "The quick brown cat"
// locale-aware comparison for correct sorting
const names = ["Élodie", "Ada", "Zara"];
names.sort((a, b) => a.localeCompare(b));
console.log(names);
Demonstrates immutability (trim 返回新 字符串), slicing 使用负 索引, 拆分 and 映射, 搜索使用包含, replacing 文本, and locale-aware 排序.
动手试一试
- 情况 Converter
Convert 文本之间 camelCase, snake_case, and 更多 — pure 字符串方法.
- Slugify
Turn 字符串到 URL-safe slugs using trim, replace, and lowercasing.
- 文本计数器
数量 characters and words — 构建 on 长度 and 拆分.
常见错误
错误写法
Calling 字符串方法不使用 capturing 返回值
正确做法
Strings are immutable. str.trim() does not change str — you must write str = str.trim() or const clean = str.trim() to use the result.
错误写法
Using == 到 compare 字符串 and 获取 surprised 通过类型 coercion
正确做法
总是 use === for 字符串 comparison. '5' === 5 是假, 但 '5' == 5 是真 due 到 coercion. For 排序, use localeCompare().
相关资源
相关速查表
- JavaScript Cheatsheet
完整引用的 字符串方法 and 示例.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。