正则常用的几种方法test、match、exec、replace

1. text()

用途:用于检验一个字符串与正则表达式是否匹配;

返回结果:Boolean类型

实例:

// 检验字符串是不是以数字结尾
var str = 'aaaa34324';
var exp = /\d$/g;
console.log(exp.test(str)); // true

2. match()

用途:用于在字符串中挑选出符合要求的值的集合;

返回结果:Array类型

实例:

// 从字符串中提取数字
var str = '现在是2020年5月19日14时14分。';
var exp = /\d+/g;
console.log(str.match(exp));
 // ["2020", "5", "19", "14", "14"]

3. exec()

用途:捕获匹配到的内容,每次只会匹配一次;

返回值:Array : [ "匹配到的内容",groups: "分组的内容有几组就有几个(括号里匹配)",index: "匹配内容的起始索引", input: "原始字符串"]

var str = "现在是2020年5月19日14时14分";
var exp = /\d+/g;
var result;
while ((result = exp.exec(str)) != null) {
  console.log(result); // 为数组,有几个属性
  console.log('lastIndex', exp.lastIndex);// 匹配到的内容末尾索引值
}

// ["2020", index: 3, input: "现在是2020年5月19日14时14分", groups: undefined]
//  lastIndex 7

//  ["5", index: 8, input: "现在是2020年5月19日14时14分", groups: undefined]
//  lastIndex 9

//  ["19", index: 10, input: "现在是2020年5月19日14时14分", groups: undefined]
//  lastIndex 12

//  ["14", index: 13, input: "现在是2020年5月19日14时14分", groups: undefined]
//  lastIndex 15

//  ["14", index: 16, input: "现在是2020年5月19日14时14分", groups: undefined]
//  lastIndex 18

4. replace()

用途:用于替换字符串中使用正则匹配到的内容;

实例:

var str = "现在是2020年5月19日4时4分";
var exp = /\d+/g;
var result = str.replace(exp, function (match, index, str) {
  // match: 匹配到的内容;index:匹配到的内容初始索引值;str:原始字符串
  if (match.length < 2) {
    return '0' + match;
  }
  return match;
});
console.log(result); // '现在是2020年05月19日04时04分'

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_陌默

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

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

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

打赏作者

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

抵扣说明:

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

余额充值