JS核心知識點梳理——正則篇(下)

正則

clipboard.png

引言

正則是一個前端必須掌握的知識。可是因爲用的少,忘了記,記了忘,致使面試常常坐蠟。這裏上篇先介紹正則的規則,下篇結合一些具體題目,帶你們從新學習鞏固一下正則,爭取面試給本身加分。html

面試題實戰

1. 匹配漢字

let regx = /^[\u4e00-\u9fa5]{0,}$/

2. 中國真實姓名

let reg = /^[\u4e00-\u9fa5]{2,4}$/

3. 字符串去重

把aaabbbccc變成abc
思路1,轉換成數組,利用set去重,再join
思路2,正則(有侷限性,必須是重複元素挨一塊兒的,且不是這種鑲嵌的'abac')前端

let a = 'aabbbccc'
let b = a.replace(/(\S)\1+/g,function (res) { //這裏\1指的是第一個分組
    return res[0]
})
console.log(b) //'abc'

4.轉駝峯

var s1 = "get-element-by-id"; 給定這樣一個連字符串,寫一個function轉換爲駝峯命名法形式的字符串 getElementById面試

let a = 'get-element-by-id'
    // 這個題目若是想分割單詞是比較麻煩的
    let f = function(s) {
        return s.replace(/-\w/g, function(x) {
            return x.slice(1).toUpperCase();
        })
    }
    console.log(f(a)) //getElementById

5. 日期格式化

2017-05-11轉換成5/11/2017數組

let a = '2017-05-11'
let reg = /(\d{4})-(\d{2})-(\d{2})/g
b=a.replace(reg,function (res, g1, g2, g3) {
    return `${g2.slice(1)}/${g3}/${g1}`
})
console.log(b) //5/11/2017

6. JS實現千位分隔符

var a = '1234567'
    var reg = /\d{1,3}(?=(\d{3})+$)/g
    var b = a.replace(reg,function (res,group,index) { //若是有?的話分組指的是最後一個
    console.log(res,group,index)   //因此group永遠是4,5,6
        return res + ','
    })
    console.log(b) //1,234,567

7. 獲取 url 中的參數

let url = 'www.baidu.com?age=11&name=fyy'
let reg = /([^?&=]+)=([^?&=]+)/g
var obj = {}
url.replace(reg,function(){
    obj[arguments[1]] = obj[arguments[2]]
})
console.log(obj)

8. 驗證身份證號

身份證號碼可能爲15位或18位,15位爲全數字,18位中前17位爲數字,最後一位爲數字或者X函數

let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

9. 句子去重複單詞

「Is is the cost of of gasoline going up up」 => ""is the cost of gasoline going up""學習

let a = 'Is is the cost of of gasoline going up up'
let reg = /\b([a-z]+) \b\1/ig 
//注意不能寫成這樣let reg = /(\w)+ \1/ig 匹配單個字符是錯的,只會匹配到最後一個
//(\w+) \1/ig 這麼寫也行
let b = a.replace(reg,function (res) {
    return res.split(' ')[0]
})
console.log(b) // Is the cost of gasoline going up

10. 寫一個方法使得數字末尾的連續0變成x如0001230000變成000123xxxx

var a = '0001230000'
var b=a.replace(/(\d)\1+$/ig,function(res){
    return res.replace(/0/g,'x') //replace改變不了原字符串
})
console.log(b) //000123xxxx

11. 有效數字驗證:整數負數0小數

.能夠出現可也以不出現,可是一旦出現後面必須跟一位或者多位數字
最開始能夠有+/-也能夠沒有
整數部分,一位數能夠是0-9,多位數不能以0開頭ui

let reg = /^-?(\d|([1-9]\d+))(\.\d+)?$/

12. 字符總體替換

將'20151214'轉化爲繁體'貳零壹伍壹貳壹肆'url

var str = '20151214'
var ary = ['零','壹','貳','叄','肆','伍']
str =str.replace(/\d/g,function () {
    return ary[arguments[0]]  //參數的第一個元素就是匹配的內容
})
console.log(str) //->貳零壹伍壹貳壹肆

13. 出現字符最多的次數

let str = 'zzzzzzzzzguowoaini'
let obj = {}
str.replace(/[a-z]/ig,function () {
    let val = arguments[0]
    obj[val] >=1?obj[val]+=1:obj[val] =1
})
let max = 0
for(let key in obj){
    obj[key]>max?max=obj[key]:null
}
console.log(max)   //-->9

14.搜索高亮功能的正則分割

如今我要作一個搜索高亮功能,須要一個拆分的正則來篩選出須要高亮的文本/好比我輸入1,我須要'帳戶A同步B 121'拆分紅這個數組[‘帳戶A同步B ’,'1','2',1'] 前面的1和後面的1都要高亮spa

let reg = /(?<=1)|(?=1)/g
'帳戶A同步B 121'.split(reg)
//["帳戶A同步B ", "1", "2", "1"]

15. pug模版引擎的基本原理

咱們選用一個經典的模版引擎pug,進入它的入門指南,pug.compileFile根據傳入的字符串模版,生成了一個方法compiledFunction,compiledFunction根據傳入的數據參數,生成不一樣的html代碼。問題來了,怎麼實現compiledFunction這個函數?code

//- template.pug
p #{name}的 Pug 代碼!

const pug = require('pug');

// 編譯這份代碼
const compiledFunction = pug.compileFile('template.pug');
// 渲染一組數據
console.log(compiledFunction({
  name: '李莉'
}));
// "<p>李莉的 Pug 代碼!</p>"
// 渲染另一組數據
console.log(compiledFunction({
  name: '張偉'
}));
// "<p>張偉的 Pug 代碼!</p>"

分析:compileFile這個函數接受一個對象參數,根據屬性值,執行相應的正則替換

function compiledFunction (args) {
        let template =  'p #{age1}的 Pug 代碼!'
        //第一步,先生成標籤 <p>{name}的 Pug 代碼!<p/>
        let a = template.replace(/^([a-z]) (.+)/g,function () { //\S沒辦法匹配空格,.能夠
            return `<${arguments[1]}>${arguments[2].slice(1)}<${arguments[1]}/>`
        })
        //第二步,再替換內容
        a = a.replace(/{(.+)}/g,function (pat,group1) {
            return args[group1]
        })
        console.log(a) //<p>fyy的 Pug 代碼!<p/>
    }
    
    compiledFunction ({age1:'fyy'}) //<p>fyy的 Pug 代碼!</p>
相關文章
相關標籤/搜索