JavaScript的正则表达式

  1. /pattern/attrs
    /1232363453/i
  2. regexObj.test(str); 测试正则表达式与指定字符串是否匹配
    /2342315435/.test('2131342431');

  3. 锚点
    匹配一个位置

    • ^ : 起始位置
      /^http:/.test('http://www.163.com');
      • $ :结尾位置
        /.jpg$/.test('1.jpg');
      • -b :单词边界
        /\bis\b/.test('that is tom');
  4. 字符类
    匹配一类字符中的一个
    -[abc]:a或b或c/[abc]/.test('aadfsacscvewf');
    -[0-9]:一个数字/[0-9]/.test('1');
    -[a-z]:一个字母/[a-z]/.test('afdscvdsda');
    -.:任一字符(换行除外)/./.test('#%^$^$%$adasc231');
    -[^0-9]非数字的一个字符/[^0-9]/.test('abc');

  5. 元字符
    具有特殊意义的字符
    -\d:[0-9]/\d/.test('1ab');
    -\D:[^\d]/\D/.test('1ab');
    -\s:空白符
    -\S:[^\s]
    -\w:[A-Za-z0-9]

  6. 量词
    出现的次数
    -{m,n}:m到n次/^1\d{10}/.test('12345678892');
    -*:{0,}(0到无穷次)/\d*/.test('abc');
    -?:{0,1}(0或1次)/https?:/.test('http:www.163.com');
    -+:{1,}(1到无穷次)/\d+/.test('1abc');

  7. 转义符
    需要匹配的字符是元字符的时候
    /^http:\/\//.test('http://www.163.com');
    /@163\.com$/.test('abc@163.com');

  8. 多选分支
    代表“或”的意思
    /thi(c|n)k$/ === /thi[cn]k/
    /\.(jpg|png|jpeg|gif)$/

  9. 捕获
    保存匹配到的字符串,日后使用
    -():捕获/(.+)@(163|126|188)\.com$/
    -(?:):不捕获/(.+)@(?:163|126|188)\.com$/
    -使用:
    - 1, 2,…
    -api参数或返回值


  1. str.match(regexp);
    获取匹配的字符串
var url = 'http://blog.163.com/album?id=1#comment';
var reg = /(https?:)\/\/([^\/]+)(\/[^\?]*)?(\?[^#]*)?(#.*)?/;
var arr = url.match(reg);
var protocol = arr[1];
var host = arr[2];
var pathname = arr[3];
var search = arr[4];
var hash = arr[5];

str.replace(regexp/substr, replacement)
替换一个子串

var str = "The price of tomato is 5.";
str.replace(/(\d+)/,"$1.00"); //$1代表获取到的价格
执行结果:"The price of tomato is 5.00."
var str = "The price of tomato is 5, The price of apple is 10.";
str.replace(/(\d+)/g,"$1.00");
执行结果:"The price of tomato is 5.00, The price of apple is 10.00."
var html = '<label>网址:</label><input placeholder="以http://为起始">';
html = html.replace(/[<>]/g,function(m0){
            switch(m0){
                case '<':
                    return '&lt;';
                case '>':
                    return '&gt;';
            }
        });

regexpObj.exec(str);
更强大的检索
-更详尽的结果:index
-过程的状态:lastIndex

var reg = /(.)(\d+)/g;
        var scores = 'Tom $88, Nicholas ¥100, jack £38.';
        var result;
        while(result = reg.exec(scores)){
            console.log(result);
            console.log(reg.lastIndex);
            // reg.lastIndex += 10;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值