// 示例代码:使用正则表达式 match 方法
const str = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
const phoneRegex = /\d{3}-\d{3}-\d{4}/g;
// 使用 match 方法查找所有匹配的邮箱地址
const emails = str.match(emailRegex);
console.log("匹配到的邮箱地址:", emails); // 输出: ["example@example.com"]
// 使用 match 方法查找所有匹配的电话号码
const phones = str.match(phoneRegex);
console.log("匹配到的电话号码:", phones); // 输出: ["123-456-7890"]
// 如果没有匹配项,match 方法会返回 null
const noMatch = "This string has no matches.".match(/xyz/);
console.log("没有匹配项时返回:", noMatch); // 输出: null
str.match(regex)
:match
方法用于在字符串中搜索与正则表达式匹配的内容。如果找到匹配项,则返回一个包含所有匹配结果的数组;如果没有找到匹配项,则返回 null
。emailRegex
:用于匹配常见的电子邮件格式。phoneRegex
:用于匹配美国标准的电话号码格式(如 123-456-7890
)。g
:表示在整个字符串中查找所有匹配项,而不仅仅是第一个匹配项。console.log
打印出匹配到的结果。上一篇:js map类型数据
下一篇:js gzip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站