JavaScript 字符串
字符串是最常用的数据类型之一。JavaScript 提供了丰富的方法来操作字符串。
基础属性与方法
length — 长度
javascript
const text = 'Hello';
console.log(text.length); // 5
'你好,世界'.length; // 5 索引访问
用方括号或 charAt() 获取特定位置的字符,索引从 0 开始:
javascript
const text = 'JavaScript';
console.log(text[0]); // "J"
console.log(text[4]); // "S"
console.log(text.charAt(0)); // "J"
// 最后一个字符
console.log(text[text.length - 1]); // "t" [index] 访问一个不存在的索引返回 undefined,charAt() 返回空字符串 ''。现代代码中 [index] 更常见。
查找与判断
indexOf() / lastIndexOf()
javascript
const text = 'Hello World Hello';
text.indexOf('World'); // 6(首次出现的位置)
text.indexOf('Hello'); // 0
text.indexOf('hello'); // -1(未找到)
text.lastIndexOf('Hello'); // 12(最后一次出现的位置) includes() / startsWith() / endsWith()
javascript
const url = 'https://example.com';
url.includes('example'); // true
url.startsWith('https'); // true
url.endsWith('.com'); // true 提取子串
slice(start, end)
javascript
const text = 'JavaScript';
text.slice(0, 4); // "Java"(索引 0~3,不含 4)
text.slice(4); // "Script"(从索引 4 到末尾)
text.slice(-6); // "Script"(从倒数第 6 到末尾)
text.slice(0, -6); // "Java"(从 0 到倒数第 6) 推荐优先使用 slice() 而非 substring() 或 substr()。slice() 支持负数索引(从末尾计数),行为更直观,substr() 已被废弃。
修改与替换
replace() / replaceAll()
javascript
const text = 'The cat and the cat toy';
text.replace('cat', 'dog'); // "The dog and the cat toy"
text.replaceAll('cat', 'dog'); // "The dog and the dog toy" toUpperCase() / toLowerCase()
javascript
'hello'.toUpperCase(); // "HELLO"
'WORLD'.toLowerCase(); // "world"
// 实用:大小写不敏感的比较
const userInput = 'YES';
userInput.toLowerCase() === 'yes'; // true trim() / trimStart() / trimEnd()
去除首尾空白(空格、制表符、换行符):
javascript
' hello '.trim(); // "hello"
' hello '.trimStart(); // "hello "
' hello '.trimEnd(); // " hello"
// 常用于处理用户输入 分割与拼接
split()
将字符串按分隔符拆分为数组:
javascript
'a,b,c'.split(','); // ["a", "b", "c"]
'hello'.split(''); // ["h", "e", "l", "l", "o"]
'2026-06-02'.split('-'); // ["2026", "06", "02"] join()(数组方法)
将数组元素拼接回字符串:
javascript
['a', 'b', 'c'].join(', '); // "a, b, c"
['H', 'e', 'l', 'l', 'o'].join(''); // "Hello" 模板字面量
反引号(`)字符串支持嵌入变量和多行:
javascript
const name = '张三';
const score = 95;
const message = `学生:${name}
成绩:${score} 分
状态:${score >= 60 ? '及格' : '不及格'}`;
// 多行文字直接写,不需要 \n 字符串的不可变性
JavaScript 的字符串是**不可变(immutable)**的——所有”修改”字符串的方法实际上都返回一个新的字符串,原字符串不变:
javascript
let text = 'Hello';
text.toUpperCase();
console.log(text); // "Hello"(没变!)
text = text.toUpperCase();
console.log(text); // "HELLO"(需要重新赋值)