JavaScript正则表达式

JavaScript正则表达式




正则表达式可以被用于 RegExp 的 exec 和 test 方法以及 String 的 matchreplacesearchsplit 方法。这些方法在 JavaScript 手册中有详细的解释。



使用正则表达式的方法(函数)
在这里插入图片描述

正则表达式标志
在这里插入图片描述

正则表达式基础



  1. 创建正则表达式对象(两种创建方式)
    <script>
        // 方法一
        // 自变量
        let reg = /\bis\b/g; //g表示全文匹配
        let str = "He is a boy. This is a dog. Where is she?";
        console.log(str.replace(reg, "IS"));



        // 方法二
        // 构造函数
        let reg = new RegExp("\\bis\\b", "g");
        let str = "He is a boy. This is a dog. Where is she?";
        console.log(str.replace(reg, "IS"));
    </script>

其输出都是:He IS a boy. This IS a dog. Where IS she?




2.(1)贪婪模式:在这里插入图片描述

(2)非贪婪模式:在这里插入图片描述

看一道例题
要求:利用正则表达式将字符串“一般圆周率为3.14,也可以为3,或者3.1415”中的数值提取到一个数组中。
代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        
        let n="一般圆周率为3.14,也可以为3,或者3.1415";
        var s=n.match(/\d+(\.\d+)?/g);
        console.log(s);
    </script>
</body>
</html>
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值