学习笔记——JS中正则表达式

前端中使用正则表达式,主要在字符串的方法中和正则表达式的方法中。


一.字符串使用正则表达式 

1.match(RegExp|String)方法

返回满足表达式的字符串,默认只匹配第一个符合表达式的数据。在正则表达式中定义全局匹配,则返回一个数组。找不到返回null。

let str = "hello, world!"
let res = str.match(/e/)
console.log(res) // e

let resR = str.match(/l/) 
console.log(resR ) // l

let resArr = str.match(/l/g) 
console.log(resArr) // [l,l,l]

2.replace(RegExp|String, newValue)方法

使用第二个参数替换满足表达式的位置。找不到返回原字符串。

let str = "hello, world!"
let res = str.replace(/l/, "e")
console.log(res); // heelo, world!

let resStr = str.replace(/l/g, "e")
console.log(resStr); // heeeo, wored!

replaceAll(String|RegExp, newValue)有兼容性,并且正则表达式必须设置全局匹配,所以不建议使用。

3.search(RegExp|String)

查询满足正则表达式的字符串,在原字符串的位置,即使有多个满足,也只会返回首个位置。找不到返回-1

let str = "hello, world!"
let res = str.search(/l/)
console.log(res); // 2

4.split(RegExp|String)

根据正则表达式或字符串将原字符串分割为数组。找不到返回包含原字符串的数组

let str = "hello, world!"
let resArr = str.split(/o/)
console.log(resArr); // ["hell", ", w", "rld!"]

二.字符串使用正则表达式 

1.test(String)

判断字符串中是否有满足正则表达式的部分。有,返回true。没有,返回false。

let regT = new RegExp(/el/)
let resT = reg.test(str)
console.log(resT);  // true

let regF = new RegExp(/al/)
let resF = reg.test(str)
console.log(resF);  // false

2.exec(String)

与match差不多,返回满足表达式的数组。找不到返回null。

let reg = new RegExp(/l/)
let str = "hello, world!"
let res = reg.exec(str)
console.log(res) // ["l", index: 2, input: "hello, world!", groups: undefined]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一一GG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值