Js realize replace the native method

The question was asked today to see how js replace method of implementation, and that they tried
introduce replace manual js String object is probably this:

 string.replace(regexp, replacement)

The first argument: (regexp)

It declares RegExp object model to be replaced. If the parameter is a string, then it is as a direct amount to be retrieved text mode, without first being converted into RegExp object.

The second parameter (Replacement)

A string is a function declaration or replacement text generates replacement text. See description.

return value

A new string is replaced obtained after a match or all of the first matching regexp replacemenc.

I tried to achieve the next start thinking does not allow for regular, there are a lot of problems, after a revised ideas:

Regular use of the Exec (), split with the matching string as a parameter to the original string is divided into a plurality of arrays, and connect the string and replace the contents join together to achieve

exec () will search character string string, text and derive a regular expression that matches regexp. If exec () to find matching text, it will return a result array. Otherwise, it returns null.

To match the first array [0]: matching text,

The second element is a second subexpression matches regexp text, and so on. Typically, length of the array property declaration is the number of elements in the array. In addition to the array elements and length property, exec () also returns two properties. index property declaration is the first character of the matching text. input property refers to the string. In a non-global calls exec RegExp object () method returns an array of the same calling a method String.match () method returns.
String.prototype.replaces=function(reg,str){
    var arr = [];
    var newStr= this;
    var i= '';
    //循环到 匹配不到替换的字符串为止
    while(reg.exec(newStr)!='null') {
        /**使用try,catch是因为在循环到匹配到所有!=null下次循
        环reg.exec(newStr)[0]会报错,循环完到报错时直接return结果**/
        try{
            arr = newStr.split(reg.exec(newStr)[0]);
            newStr = arr.join(str);
            //如果该正则式子不是全局正则(/g)不作循环直接修改一次返回
            if(!reg.global){
                return newStr;
            }
        }catch(e){
            return newStr;
        }
        
    }
    
} 

console.log("我是AbCd啊abcd啊abcd".replaces(/abcd/gi,'lipengpeng'))

----------------------------------------------------

经过测试,上面代码存在的问题如下:
当正则表达式是全局时(/g)时,且只匹配到一个,会直接返回原字符串,
在循环reg.exec(newStr)时,每次结果都不一样,这里暂时不清楚原因

修改后的:
String.prototype.replaces=function(reg,str){
    var arr = [];
    var newStr= this;
    var i= '';
    var d;
    //为了防止reg.exec()每次结果不一样,直接赋给一个变量
    //这里注意给d=reg.exec()加括号, “=”的优先级低
    while((d = reg.exec(newStr))!=null) {
        try{
            arr = newStr.split(d[0]);
            newStr = arr.join(str);
            if(reg.global){
                return newStr;
            }else{
                break;
            }
        }catch(e){
            console.log(e)
        }
        
    }
    
}

---------------------------------split line--------------- ----------------------

After the above code continues tested if the regular case-insensitive match (/ i) does not match the global turn, results global replacement. Adding a non-global code, not the case in a global or non-global tube (regular already been processed), the final code:

    String.prototype.replaces = function(reg, str) {
        var arr = [];
        var newStr = this;
        var i = '';
        var d;
        while((d = reg.exec(newStr)) != null) {
            //debugger
            try {
                //console.log(d)
                if(reg.global) {
                    arr = newStr.split(d[0]);
                    newStr = arr.join(str);
                } else {
                    
                    var index = d['index'];
                    var lastindex = (+index) + (+d[0].length);
                    var preStr = newStr.slice(0, index);
                    var nextStr = newStr.slice(lastindex);
                    newStr = preStr + str + nextStr;
                    break;

                }

            } catch(e) {
                console.log(e)
            }

        }
        return newStr

    }

    var s = "我是A,c,a,cc,c,c,cc,a".replaces(/a/ig, 'b')
    console.log(s)

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/11965263.html