正则表达式是JavaScript中强大的文本处理工具,掌握它可以大大提高开发效率。本指南将带你从零开始学习JavaScript正则表达式。
正则表达式(Regular Expression)是一种用于匹配字符串中字符组合的模式。在JavaScript中,正则表达式也是对象。
在JavaScript中有两种创建正则表达式的方式:
// 字面量方式
let regex = /pattern/flags;
// 构造函数方式
let regex = new RegExp('pattern', 'flags');
测试字符串是否匹配正则表达式,返回true或false。
let str = 'hello world';
let result = /hello/.test(str); // true
执行正则表达式匹配,返回匹配结果的数组或null。
let str = 'hello world';
let result = /hello/.exec(str);
// 返回['hello', index: 0, input: 'hello world']
字符串也有几个方法可以使用正则表达式:
直接匹配字符本身:
/abc/ // 匹配"abc"
使用特殊字符实现更复杂的匹配:
指定匹配字符的数量:
标志可以改变正则表达式的行为:
let emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
let phoneRegex = /^1[3-9]\d{9}$/;
let url = 'https://www.example.com/page';
let domain = url.match(/https?:\/\/([^/]+)/)[1];
// 返回"www.example.com"
通过本指南,你应该已经掌握了JavaScript正则表达式的基础知识。正则表达式虽然看起来复杂,但通过不断练习,你会发现它在前端开发中的强大作用。