返回
程序员必备:JavaScript 正则表达式语法和 API 大全
前端
2024-02-15 15:24:57
在 JavaScript 中,正则表达式 (Regular Expression) 是一种强大的工具,可用于处理字符串操作、数据验证和模式匹配等任务。本文将为您提供一份 JavaScript 正则表达式语法和 API 知识点整理,帮助您快速掌握正则表达式的使用技巧。
一、参考资料
- 正则表达式验证网址
- 学习 Vue 中那些正则表达式
二、语法介绍
创建正则表达式
const regex = new RegExp(pattern, flags);
其中:
pattern
:正则表达式模式字符串。flags
:正则表达式标志字符串。
没有标志的搜索
const regex = /pattern/;
三、常用 API
exec()
方法
const regex = /pattern/;
const result = regex.exec(string);
其中:
string
:要搜索的字符串。result
:一个数组,包含匹配的结果。
test()
方法
const regex = /pattern/;
const result = regex.test(string);
其中:
string
:要搜索的字符串。result
:一个布尔值,指示是否找到了匹配项。
match()
方法
const regex = /pattern/;
const result = string.match(regex);
其中:
string
:要搜索的字符串。result
:一个数组,包含匹配的结果。
replace()
方法
const regex = /pattern/;
const result = string.replace(regex, replacement);
其中:
string
:要搜索的字符串。regex
:正则表达式模式字符串。replacement
:替换匹配项的字符串。
split()
方法
const regex = /pattern/;
const result = string.split(regex);
其中:
string
:要搜索的字符串。regex
:正则表达式模式字符串。
四、示例
验证电子邮件地址
const regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const result = regex.test(email);
其中:
email
:要验证的电子邮件地址。result
:一个布尔值,指示电子邮件地址是否有效。
提取字符串中的数字
const regex = /\d+/g;
const result = string.match(regex);
其中:
string
:要提取数字的字符串。regex
:正则表达式模式字符串。result
:一个数组,包含匹配的数字。
替换字符串中的所有空格
const regex = /\s+/g;
const result = string.replace(regex, "");
其中:
string
:要替换空格的字符串。regex
:正则表达式模式字符串。result
:替换空格后的字符串。
总结
以上是 JavaScript 正则表达式语法和 API 知识点整理,希望对您有所帮助。正则表达式是一门强大的工具,掌握它可以帮助您轻松处理字符串操作、数据验证和模式匹配等任务。
如果您想了解更多有关 JavaScript 正则表达式的知识,可以参考以下资源:
- MDN Web Docs:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
- Regular Expressions 101:https://www.regular-expressions.info/