📝 第七章:字符串与正则表达式

掌握字符串处理和正则表达式的高级用法

7.1 模板字符串与标签函数

模板字符串

// 传统字符串
const name = 'John';
const message = 'Hello, ' + name + '!'; // 'Hello, John!'

// 模板字符串
const message2 = `Hello, ${name}!`; // 'Hello, John!'

// 多行字符串
const multiLine = `
    Hello
    World
`;

// 表达式
const a = 10;
const b = 20;
const sum = `${a} + ${b} = ${a + b}`; // '10 + 20 = 30'

标签函数

// 标签函数
function highlight(strings, ...values) {
    let result = '';
    strings.forEach((string, index) => {
        result += string;
        if (values[index] !== undefined) {
            result += `<span style="background: yellow;">${values[index]}`;
        }
    });
    return result;
}

const name = 'John';
const age = 30;
const result = highlight`Hello, ${name}! You are ${age} years old.`;
console.log(result); // Hello, <span style="background: yellow;">John! You are <span style="background: yellow;">30 years old.

7.2 字符串处理方法

常用字符串方法

方法 描述 示例
includes() 检查是否包含子字符串 'hello'.includes('ell') → true
startsWith() 检查是否以子字符串开头 'hello'.startsWith('he') → true
endsWith() 检查是否以子字符串结尾 'hello'.endsWith('lo') → true
trim() 去除首尾空白 ' hello '.trim() → 'hello'
trimStart() 去除开头空白 ' hello'.trimStart() → 'hello'
trimEnd() 去除结尾空白 'hello '.trimEnd() → 'hello'
replace() 替换第一个匹配项 'hello'.replace('l', 'x') → 'hexlo'
replaceAll() 替换所有匹配项 'hello'.replaceAll('l', 'x') → 'hexxo'
split() 分割字符串 'a,b,c'.split(',') → ['a', 'b', 'c']
join() 连接数组为字符串 ['a', 'b', 'c'].join(',') → 'a,b,c'
substring() 提取子字符串 'hello'.substring(1, 4) → 'ell'
slice() 提取子字符串 'hello'.slice(1, 4) → 'ell'
toLowerCase() 转为小写 'HELLO'.toLowerCase() → 'hello'
toUpperCase() 转为大写 'hello'.toUpperCase() → 'HELLO'

7.3 正则表达式基础

正则表达式是用于匹配字符串中字符组合的模式。

创建正则表达式

// 字面量语法
const regex1 = /pattern/flags;

// 构造函数语法
const regex2 = new RegExp('pattern', 'flags');

// 示例
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const phoneRegex = /^1[3-9]\d{9}$/;

常用标志

标志 描述
g 全局匹配
i 忽略大小写
m 多行匹配
s 允许 . 匹配换行符
u Unicode 模式
y 粘性匹配

常用方法

// test() - 检查是否匹配
const regex = /\d+/;
console.log(regex.test('123')); // true

// exec() - 执行匹配
const result = regex.exec('abc123def456');
console.log(result); // ['123', index: 3, input: 'abc123def456', groups: undefined]

// match() - 字符串方法
const str = 'abc123def456';
console.log(str.match(/\d+/g)); // ['123', '456']

// replace() - 替换
const replaced = str.replace(/\d+/g, 'X');
console.log(replaced); // 'abcXdefX'

7.4 ES2026 新特性

正则表达式 /v 标志

// /v 标志 - Unicode 属性类增强
const regex = /\p{Emoji}/v;
console.log(regex.test('😊')); // true

const regex2 = /\p{Script=Han}/v; // 匹配汉字
console.log(regex2.test('你好')); // true

重复命名捕获组

// 重复命名捕获组
const regex = /(?<digit>\d)+/;
const result = regex.exec('12345');
console.log(result.groups.digit); // '5'(最后一个匹配的数字)

// 在 replace 中使用
const str = '123-456-789';
const replaced = str.replace(/(?<area>\d{3})-(?<local>\d{3})-(?<line>\d{3})/, 'Area: $<area>, Local: $<local>, Line: $<line>');
console.log(replaced); // 'Area: 123, Local: 456, Line: 789'

动手练习

练习 1:模板字符串

  1. 使用模板字符串创建动态文本
  2. 创建多行模板字符串
  3. 在模板字符串中使用表达式

练习 2:字符串方法

  1. 使用 includes()、startsWith()、endsWith() 检查字符串
  2. 使用 trim()、trimStart()、trimEnd() 处理空白
  3. 使用 replace()、replaceAll() 替换字符串
  4. 使用 split()、join() 处理字符串数组

练习 3:正则表达式

  1. 创建正则表达式匹配邮箱
  2. 创建正则表达式匹配手机号
  3. 使用正则表达式替换文本
  4. 测试 ES2026 的 /v 标志