返回

JavaScript正则表达式:摆脱面向搜索引擎编程

前端




JavaScript正则表达式:摆脱面向搜索引擎编程

前言

本文介绍了对正则表达式的基本使用与总结,希望之后再用到正则时,不再面向搜索引擎编程😃。

首先推荐两个比较好的学习正则的网站:

  • 在线编辑正则表达式
  • 胶囊编程正则表达式学习

正则对象方法

方法名
exec() 在字符串中执行搜索,并返回第一个匹配项
test() 在字符串中执行搜索,并返回布尔值,表示是否有匹配项
match() 在字符串中执行搜索,并返回所有匹配项
search() 在字符串中执行搜索,并返回第一个匹配项的索引位置
replace() 在字符串中执行搜索,并用新字符串替换所有匹配项
split() 在字符串中执行搜索,并按匹配项将字符串分割成数组

正则表达式语法

语法
. 匹配任何一个字符
^ 匹配字符串的开头
$ 匹配字符串的结尾
* 匹配前面的子表达式零次或多次
+ 匹配前面的子表达式一次或多次
? 匹配前面的子表达式零次或一次
[] 匹配指定范围内的字符
[^] 匹配指定范围之外的字符
{} 指定重复次数
() 对子表达式进行分组
` `

正则表达式实例

// 匹配数字
const re = /\d+/;
const str = "123456";
const result = str.match(re);
console.log(result); // ["123456"]

// 匹配字母
const re = /[a-zA-Z]+/;
const str = "hello world";
const result = str.match(re);
console.log(result); // ["hello", "world"]

// 匹配邮箱地址
const re = /\w+@\w+\.\w+/;
const str = "john@example.com";
const result = str.match(re);
console.log(result); // ["john@example.com"]

// 匹配URL地址
const re = /(https?://)?(www\.)?[\w\d\-_]+(\.\w+)+(\/[\w\d\-_]+)*(\?[\w\d\-_]+=[^&\r\n]*)?/;
const str = "https://www.example.com/path/to/file?query=string";
const result = str.match(re);
console.log(result); // ["https://www.example.com/path/to/file?query=string", "https://", "www.", "example.com", "/path/to/file", "?query=string"]

结语

正则表达式是JavaScript中非常重要的工具,掌握了正则表达式,可以大大提高我们的编程效率。希望本文能对大家有所帮助。