正则表达式使用方法及好用的小工具

正则表达式使用方法及好用的小工具

正则表达式

正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

常用方法

 //test()方法 查找是否有匹配的值 //该方法返回true或者false
        //注意用法 正则表达式在前 语法: 
        // pattern.test(str)
        var pattern1 = /world/;
        var str1 = "hello world  ,and the world is beautiful!";
        console.log(pattern1.test(str1)); //true

        //exec()方法 查询匹配值的信息
        //注意用法 正则表达式在前 语法: 
        // pattern.test(str)
        var pattern2 = /world/; //该方法有没有g不影响结果 i有效
        var str2 = "hello world  ,and the world is beautiful!";
        console.log(pattern2.exec(str2)); //返回第一个匹配值的伪数组
        //["world", index: 6, input: "hello world  ,and the world is beautiful!", groups: undefined]


        //match()方法 
        //与exec()不同在于该方法属于string的正则表达方法,exec属于正则表达式方法
        //用法也不同  全局变量g有效  g为全局 i为不区分大小写
        var pattern3 = /world/gi;
        var str3 = "hello World  ,and the world is beautiful!";
        console.log(str3.match(pattern3)); //(2) ["World", "world"] 返回匹配值伪数组

        //search()方法 返回匹配值的索引值
        var pattern4 = /world/i;
        var str4 = "hello World  ,and the world is beautiful!";
        console.log(str4.search(pattern4)); // 6

        //replace()方法 替换匹配值 但不改变原来字符串
        var pattern5 = /world/i;
        var str5 = "hello World  ,and the world is beautiful!";
        console.log(str5.replace(pattern5, "test")); //hello test  ,and the world is beautiful!
        console.log(str5); //hello World  ,and the world is beautiful!


好用的工具网址推荐

生成正则表达式:
https://c.runoob.com/front-end/854

查看正则表达式语义:
https://regexper.com/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值