10、JavaScript字符串方法中的正则表达式
2025/9/23大约 2 分钟
JavaScript字符串方法中的正则表达式
JavaScript 的 String 对象提供了几个使用正则表达式的方法,这些方法可以让我们轻松地进行字符串搜索、替换和提取操作。本文将详细介绍这些方法的使用。
1. String.prototype.match()
match()
方法检索返回一个字符串匹配正则表达式的结果。
基本用法
const text = 'The quick brown fox jumps over the lazy dog.';
const regex = /[a-z]+/g;
const matches = text.match(regex);
console.log(matches);
// 输出: ['he', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
不带全局标志的匹配
如果正则表达式没有 g
标志,match()
将返回第一个完整匹配及其相关的捕获组:
const text = 'The quick brown fox';
const regex = /quick (\w+)/;
const result = text.match(regex);
console.log(result);
// 输出: ['quick brown', 'brown', index: 4, input: 'The quick brown fox', groups: undefined]
2. String.prototype.search()
search()
方法执行正则表达式和 String 对象之间的搜索匹配,返回第一个匹配的索引,如果未找到则返回 -1。
const text = 'The quick brown fox jumps over the lazy dog.';
const regex = /brown/;
const position = text.search(regex);
console.log(position); // 输出: 10
3. String.prototype.replace()
replace()
方法返回一个由替换值替换部分或所有匹配的模式后的新字符串。
基本替换
const text = 'The quick brown fox';
const regex = /brown/;
const newText = text.replace(regex, 'red');
console.log(newText); // 输出: 'The quick red fox'
全局替换
const text = 'apple, banana, apple, orange';
const regex = /apple/g;
const newText = text.replace(regex, 'pear');
console.log(newText); // 输出: 'pear, banana, pear, orange'
使用捕获组
const date = '2025-09-23';
const regex = /(\d{4})-(\d{2})-(\d{2})/;
// 将日期格式从 YYYY-MM-DD 转换为 DD/MM/YYYY
const formattedDate = date.replace(regex, '$3/$2/$1');
console.log(formattedDate); // 输出: '23/09/2025'
使用回调函数
const text = 'The QUICK brown FOX';
const regex = /[A-Z]+/g;
const result = text.replace(regex, match => match.toLowerCase());
console.log(result); // 输出: 'The quick brown fox'
4. String.prototype.replaceAll()
replaceAll()
方法返回一个新字符串,其中所有匹配的模式都被替换项替换。与 replace()
不同的是,当使用字符串作为模式时,它会替换所有出现的模式。
const text = 'apple, banana, apple, orange';
// 使用字符串
const newText1 = text.replaceAll('apple', 'pear');
console.log(newText1); // 'pear, banana, pear, orange'
// 使用正则表达式(必须使用全局标志)
const regex = /a\w+/g;
const newText2 = text.replaceAll(regex, 'fruit');
console.log(newText2); // 'fruit, bfruit, fruit, orfruit'
5. String.prototype.split()
split()
方法使用指定的分隔符字符串将一个 String 对象分割成子字符串数组。
const text = 'The quick brown fox';
// 使用空格分割
const words = text.split(' ');
console.log(words); // ['The', 'quick', 'brown', 'fox']
// 使用正则表达式分割
const regex = /\s+/; // 匹配一个或多个空白字符
const words2 = text.split(regex);
console.log(words2); // ['The', 'quick', 'brown', 'fox']
掌握这些字符串方法可以帮助你更有效地处理文本数据。在下一篇文章中,我们将探讨 JavaScript 的 RegExp 对象及其方法。