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