字符串 and 文本
Master 文本 in code: 字符串 creation, concatenation, slicing, and 常见方法每个 developer uses daily.
你将学到
- 如何 创建 and 格式字符串使用 quotes and template literals
- 字符串 concatenation and interpolation 技巧
- Accessing characters and substrings 使用 indexing and slicing
- 常见字符串方法: 长度, 拆分, replace, trim, 包含
- 为什么字符串 immutability matters for 性能 and safety
概念讲解
Strings and Text
string 是一种 sequence of characters — text, in everyday terms. Strings are everywhere in programming: user input, file contents, URLs, error messages, and JSON data are all strings. Because text is the most common data type you will handle, mastering string operations is essential.
Creating Strings
JavaScript lets you create strings with single quotes, double quotes, or backticks. Backticks create template literals, which support multi-line text and interpolation — embedding expressions directly inside the string with ${}:
const single = 'Hello';
const double = "World";
const name = "Ada";
const greeting = `Hello, ${name}!`; // "Hello, Ada!"
Concatenation and Interpolation
Concatenation joins strings with +. Interpolation embeds values inside a template literal. Interpolation is almost always clearer, especially when combining multiple values:
const user = "Grace";
const count = 5;
// Concatenation — works but gets messy:
const msg1 = "User " + user + " has " + count + " items.";
// Interpolation — cleaner and more readable:
const msg2 = `User ${user} has ${count} items.`;
Accessing and Slicing
You can access individual characters by index (starting at 0) and extract substrings with slice, substring, or substr:
const text = "JavaScript";
text[0]; // "J"
text.length; // 10
text.slice(0, 4); // "Java"
text.slice(-6); // "Script" (negative = from end)
Common Methods
Strings come with built-in methods — functions attached to the string object. The most frequently used ones include toUpperCase(), toLowerCase(), trim(), 拆分(), replace(), 包含(), and indexOf(). These methods return *new* strings; they never modify the original, because strings are immutable in JavaScript.
Immutability
Immutability means a string cannot be changed after creation. Methods like toUpperCase() return a brand-new string rather than altering the original. This is a safety feature: it prevents accidental mutations and makes string behavior predictable. When you need to "modify" a string, you reassign the variable to the result of the method call.
Understanding strings deeply will save you countless hours. Most real-world bugs in web applications involve text processing — parsing input, validating formats, or transforming data for display.
示例代码
const sentence = " The quick brown fox ";
// Trim whitespace from both ends
const clean = sentence.trim(); // "The quick brown fox"
// Split into words, then reverse and rejoin
const words = clean.split(" "); // ["The", "quick", "brown", "fox"]
const reversed = words.reverse().join(" "); // "fox brown quick The"
// Replace a word (only the first match)
const updated = clean.replace("brown", "red"); // "The quick red fox"
// Check if the string contains a substring
const hasFox = clean.includes("fox"); // true
// Extract a portion
const middle = clean.slice(10, 15); // "brown"
console.log(reversed, updated, hasFox, middle);
这个示例 demonstrates trimming, 拆分, reversing, replacing, 搜索, and slicing — six 的大多数常见字符串操作你 将 use in 真实项目.
动手试一试
- 情况 Converter
Transform 文本之间 camelCase, snake_case, kebab-情况 and 更多 — pure 字符串 manipulation in 操作.
- 文本计数器
数量 characters, words, and 行 in 任何文本. Internally 它 uses 拆分, 长度, and trim.
常见错误
错误写法
Expecting 字符串方法到 修改原始变量.
正确做法
字符串是 不可变. 方法返回新 字符串. 总是 capture result: 文本 = 文本.trim(), 不只是文本.trim().
错误写法
Using + 到构建复杂字符串相反的 template literals.
正确做法
Use template literals (backticks) 使用 ${} interpolation. 它们是 更多 readable and 更少错误-prone than chaining + 运算符.
错误写法
Forgetting 那个字符串 indexing 开始 at 0.
正确做法
首先 character 是文本[0], 不文本[1]. 最后是 文本[文本.长度 - 1]. Off-通过-one 错误 in 字符串 slicing 是 extremely 常见.
相关资源
相关速查表
- JavaScript Cheatsheet
完整引用 for 所有字符串方法 and template literal 语法.
练习 字符串 and 文本
10 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。