正規表示式應用收集

看風景就發表於2017-12-14

1.千分位分割,手機號碼分割

//千分位分割組替換
var n = '1234321789.33',
    reg = /(\d{1,3})(?=(\d{3})+(?:\.|$))/g;

n = n.replace(reg,'$1,');
console.log('n: ' + n);

//千分位分割單詞邊界
var m = '1234321789.33',
    reg = /\B(?=(\d{3})+(?!\d))/g;

m = m.replace(reg,',');
console.log('m: ' + m)

//手機號分割單詞邊界
var p = '18810808376',
    reg = /\B(?=(\d{4})+(?!\d))/g;

p = p.replace(reg,' ');
console.log('p: ' + p);

2.獲取url引數

function queryAll(){
    var src = location.search || location.hash,
        reg = /[?&]([^&]+)=([^&]+)/g,
        res = null,
        obj = {};
    while(res = reg.exec(src)){
        obj[res[1]] = decodeURIComponent(res[2].replace(/\+/g,' '));
    }
    return obj;
}

function queryOne(key){
    var src = location.search || location.hash,
        reg = new RegExp('[?&]'+key+'=([^&]+)'),
        match = reg.exec(src);

    return match == null ? null : decodeURIComponent(match[1].replace(/\+/g,' ')) ;
}

3.replace的正則形式

//寫format方法

function format(s){
  var args = arguments;
  return s.replace(/\{(\d+)\}/,function($0,$1){
    return args[($1 | 0) + 1] || '';
  })
}

format("{0} love {1}.",'I','You')  //I love you

 

相關文章