js实现匹配
JavaScript 实现字符串匹配
JavaScript 提供了多种方法来实现字符串匹配,包括使用内置方法和正则表达式。
使用 String.prototype.includes() 方法
const str = "Hello, world!";
const substring = "world";
const isMatch = str.includes(substring); // true
includes() 方法检查字符串是否包含指定的子字符串,返回布尔值。
使用 String.prototype.indexOf() 方法
const str = "Hello, world!";
const substring = "world";
const position = str.indexOf(substring); // 7
indexOf() 方法返回子字符串首次出现的索引,未找到则返回 -1。
使用 String.prototype.match() 方法
const str = "Hello, world!";
const regex = /world/;
const result = str.match(regex); // ["world", index: 7, input: "Hello, world!"]
match() 方法使用正则表达式匹配字符串,返回匹配结果数组或 null。
使用 String.prototype.search() 方法
const str = "Hello, world!";
const regex = /world/;
const position = str.search(regex); // 7
search() 方法使用正则表达式搜索字符串,返回匹配的索引或 -1。
使用 RegExp.prototype.test() 方法
const str = "Hello, world!";
const regex = /world/;
const isMatch = regex.test(str); // true
test() 方法测试正则表达式是否匹配字符串,返回布尔值。

使用 RegExp.prototype.exec() 方法
const str = "Hello, world!";
const regex = /world/;
const result = regex.exec(str); // ["world", index: 7, input: "Hello, world!"]
exec() 方法在字符串中执行正则表达式搜索,返回匹配结果数组或 null。
正则表达式高级匹配
匹配多个结果
const str = "The rain in Spain falls mainly in the plain";
const regex = /ain/g;
const matches = str.match(regex); // ["ain", "ain", "ain"]
使用全局标志 g 可以匹配所有符合条件的子字符串。
使用捕获组
const str = "John Doe";
const regex = /(\w+)\s(\w+)/;
const result = regex.exec(str);
// ["John Doe", "John", "Doe", index: 0, input: "John Doe"]
圆括号 () 用于创建捕获组,匹配的子字符串会被单独返回。

不区分大小写匹配
const str = "Hello, World!";
const regex = /world/i;
const isMatch = regex.test(str); // true
使用 i 标志进行不区分大小写的匹配。
性能考虑
对于简单的子字符串检查,includes() 和 indexOf() 通常比正则表达式更快。正则表达式适合更复杂的模式匹配场景。
字符串方法 vs 正则表达式
- 字符串方法:简单、高效,适合固定子字符串匹配
- 正则表达式:功能强大,适合模式匹配和复杂规则
实际应用示例
验证电子邮件格式
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
提取URL中的域名
function getDomain(url) {
const regex = /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/;
const match = url.match(regex);
return match ? match[1] : null;
}
替换字符串中的模式
const str = "The quick brown fox jumps over the lazy dog";
const newStr = str.replace(/fox/, "cat"); // "The quick brown cat jumps over the lazy dog"






