5种JavaScript 正则表达式的方法

web前端开发

共 2892字,需浏览 6分钟

 · 2021-08-20

现在 JavaScript 非常强大,可以用它做很多事情,移动应用程序、网站、网络应用程序、游戏,甚至可以包括人工智能。JavaScript 生态系统有很多脚本库和框架,可以用它来做什么事情。
除此之外,JavaScript 每年都会有一些新的非常有用功能增加,感谢 ECMAScript 规范,现在有很多方法可以用于 JavaScript 中的不同数据类型。
在本文中,将介绍一些 JavaScript 中的编写正则表达式的常见用法。

1、match()

match() 与字符串一起使用以检查字符串和正则表达式 regex 之间的匹配,以正则表达式为参数。
语法:
str.match(regex);

方法返回 3 个可能的值:

  • 如果正则表达式包含一个 g 标记,即为全局匹配,它将返回一个包含所有匹配项的数组,没捕获组信息;

  • 如果正则表达式没有 g 标记,它将返回一个包含第一个匹配项和其相关的捕获组的数组;

  • 如果根本没有匹配项,则返回 null 。

groups:一个命名捕获组的对象,其键是名称,值为捕获组,如果未定义命名捕获组,则为 undefined。

带有标记 g 的实例代码:

const strText = "Hello China";const regex = /[A-Z]/g; // 大写字母正则表达式console.log(strText.match(regex)); // [ 'H', 'C' ]

没有标记 g 的实例代码:

const text = 'Hello World';const regex = /[A-Z]/; //Capital letters regex.console.log(text.match(regex)); // [ 'H', index: 0, input: 'Hello China', groups: undefined ]

当没有匹配的实例代码:

const strText = "hello china";const regex = /[A-Z]/; // 大写字母正则表达式console.log(strText.match(regex)); // null

2、test()

test() 用于测试指定字符串和正则表达式之间是否匹配,接受一个字符串作为其参数,并根据是否匹配返回 true 或 false 。

假设在下面的字符串 strText 中检测单词 china 是否存在。可以为查找单词创建一个正则表达式并测试该正则表达式和字符串 strText 之间是否匹配。

const strText = "hello china";const regex = /china/;console.log(regex.test(strText)); // true

下面是没有匹配的实例代码:

const strText = "hello China";const regex = /china/;console.log(regex.test(strText)); // false

从上面代码可以看到,大小写是会影响匹配的结果,如果需要忽略大小写,则需要使用标记 i,如下代码:

const strText = "hello China";const regex = /china/i;console.log(regex.test(strText)); // true
请注意,在语法上 .match() 与 .test() 在使用上是 “相反” 的

3 、search()

search() 方法是一个字符串方法,可以将其与正则表达式一起使用。可以将正则表达式作为参数传递给它,以在字符串中搜索匹配项。

方法返回第一个匹配项在整个字符串中的位置(索引),如果没有匹配项,则返回 -1。

匹配的实例:

const strText = "hello china,i love china";const regex = /china/;console.log(strText.search(regex)); // 6

没有匹配的实例:

const strText = "hello china,i love china";const regex = /devpoint/;console.log(strText.search(regex)); // -1

4、 replace()

replace() 是在字符串中搜索指定的值或正则表达式并将其替换为另一个值,方法接受两个参数:

  1. 要搜索的值

  2. 要替换的新值

方法返回一个包含被替换后的新字符串,需要注意的是,它不会改变原始字符串,并且只会替换搜索到的第一个值。

实例代码:

const strText = "hello world,i love world";const regex = /world/;console.log(strText.replace(regex, "china")); // hello china,i love world

5、replaceAll()

replaceAll() 类似于方法 replace() ,但它允许替换字符串中所有匹配的值或正则表达式。

它接受两个参数:

  1. 要搜索的值,如果是正则,则必须带上全局标记 g

  2. 要替换的新值

它返回一个包含所有新值的新字符串,同样也不会更改原始字符串。

实例代码:

const strText = "hello world,i love world";const regex = /world/g;console.log(strText.replaceAll(regex, "china")); // hello china,i love china

等效于如下代码:

const strText = "hello world,i love world";console.log(strText.replaceAll("world", "china")); // hello china,i love china
通过正则查找替换,在正则表达式中加上全局标记 g , 同样可以替换所有符合正则条件的字符串,如下代码:
const strText = "hello world,i love world";const regex = /world/g;console.log(strText.replace(regex, "china")); // hello china,i love china

总结

本文介绍了可以与正则表达式一起使用的常用方法,在项目中常用且有用,如表单验证、密码验证等。


学习更多技能

请点击下方公众号


浏览 11
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报