正則表達(dá)式使用實例

  • 查找數(shù)字
    原生
找出字符串中的數(shù)字
(function(){
    function num(str) {
        let arr = [];
        let temp = '';
        for(let i = 0; i < str.length; i++) {
            if(str.charAt(i) <= '9' && str.charAt(i) >= '0') {
                //arr.push(str.charAt(i))
                temp += str.charAt(i);
            }
            else {
                if(temp){
                    arr.push(temp);
                    temp = '';     } } }
        if(temp){
            arr.push(temp);

        }
         console.log(arr)
    }
    let str = '123asf434sf43621wq345';
    num(str);
})();

正則表達(dá)式 /\d+/g

    let str1 = '123asf434sf43621wq345';
    let re = /\d+/g;
    console.log(str.match(re))
  • 敏感詞過濾
(function () {
    let str = '嘿嘿中國呵呵呵少年sp';
    let re = /嘿嘿|(zhì)呵呵呵|sp/g;
    let result = str.replace(re,function (str0,str1,str2,str3) {
        let temp = '';
        if(str){
            for(let i = 0; i < str.length; i++){
                temp+='*'
            } }
        // console.log(temp)
        return temp;
    });
    console.log(result); //**中國***少年**
})();
  • 找出重復(fù)次數(shù)最多的字符以及次數(shù)
(function(){
    // let str = 'asdaaassseedddddaffgyDXCvSSS';
    let str = 'aSdv';
    let re = /(\w)\1*/ig;
    //將字符串進(jìn)行排序,把相同的字符放在一起
    let arr = str.toLowerCase().split('');
    // console.log(arr)
    str = arr.sort().join('');
    // console.log(str)
    let MaxLen = 0;
    let MaxValue = '';

    str.replace(re,function($0,$1,$2,$3,$4){
        console.log(arguments)
        if($0.length > MaxLen) {
            MaxLen = $0.length;
            MaxValue = $1;
        }else if($0.length === MaxLen){MaxValue += $1}
    })
    console.log(MaxValue+'.....'+MaxLen)
})();
  • 去掉空格
(function(){
    let str = ' as  as d ';
    // let re = /^\s|\s/g; //去除全部空格
    let re = /^\s+|\s+$/g; //去除首尾空格
    console.log('('+str.replace(re,'')+')')
})()

trim用法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容