【JS学习笔记十一】正则表达式

RegExp 正则表达式

  1. 作用: 匹配特殊字符或有特殊搭配原则的字符的最佳选择。
  2. 两种创建方式
    • 直接量 var reg = /pattern/;
    • new RegExp(); var reg = new RegExp('pattern');
      个人推荐用直接量

示例:

  1. 将 ‘the-first-name’ 转换成小驼峰形式:
 <script>
        var reg = /-(\w)/g;
        var str = "the-first-name";
        console.log(str.replace(reg, function($, $1){
            return $1.toUpperCase();
        }));
    </script>

输出: theFirstName

  1. 100000000 转换为 100.000.000
  <script>
       var str = "100000000";
       var reg = /(?=(\B)(\d{3})+$)/g;
       console.log(str.replace(reg,"."));
    </script>
发布了69 篇原创文章 · 获赞 96 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40693643/article/details/102994062