数组replace的终极用法

单个替换

var str="2018&08&08";
        var num=0;
        var res=str.replace(/\D/g,function(mathed,index,str){
            if(num==0){
                num++
                return "-";
            }
            if(num==1){
                num++;
                return "=";
            }
        })
        //res="2018-08=08"

将所有foo(a,b,c)变成foo(b,a,c)

    var codestr="foo(a1,b1,c1)"
    codestr.replace(/foo\(([^,]+),([^,]+),([^,]+)\)/,"foo($2,$1,$3)");
    //foo(b1,a1,c1)

将所有的big,bog,beg,bag都改成bug

//将所有的big,bog,beg,bag都改成bug
    var str="hellobig bug bag big bug";
    str.replace(/(\s+)(b(a|e|i|o)g)\b/g,function(){
        console.log(arguments);
    })
    //看一下这个函数所传入的参数
    //Arguments(6) [" bag", " ", "bag", "a", 12, "hellobig bug bag big bug", callee: ƒ, Symbol(Symbol.iterator): ƒ]
    //Arguments(6) [" big", " ", "big", "i", 16, "hellobig bug bag big bug", callee: ƒ, Symbol(Symbol.iterator): ƒ]

    str.replace(/(\s+)(b(a|e|i|o)g)\b/g,function(matched,s1){
        return s1+"bug";
    })
    //hellobig bug bug bug bug

猜你喜欢

转载自blog.csdn.net/qq_43031907/article/details/82020645