zoukankan      html  css  js  c++  java
  • 手写replace方法

    方法replace,作为字符串中一个常用的函数吸引了我的好奇,
    为了弄清它的核心原理,在这里,我就手撸一个replace方法;

    replace(reg,callback)

    reg: 作为匹配的正则
    callback:回调函数

    (function (){
        // 将str中的v1替换成v2
        function swap(str,v1,v2) {
            let index = str.indexOf(v1);
            return str.substring(0,index) + v2 + str.substring(index + v1.length);
        }
        function replace(reg,callback) {
            let isGlobal = reg.global,
                _this = this.substring(0),
                arr = reg.exec(this);
            while(arr) {
                if (typeof callback === "function") {
                    let result = callback.apply(window,arr);
                    _this = swap(_this,arr[0],result);
                }
                arr = reg.exec(this);
                if (!isGlobal) {
                    break;
                }
            }
            return _this;
        }
        String.prototype.myreplace = replace;
    })();
    

    看下是否能跑?

    let msg = "yi1234threeyour1233";
    msg = msg.replace(/((d){4})/g,function(context,group1){
        return "四个数字";
    });
    console.log(msg);
    //yi这里有四个数字threeyour这里有四个数字
    
    慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
  • 相关阅读:
    CSS3_02之2D、3D动画
    CSS3_01之选择器、Hack
    css_04之显示、定位
    css_03之文本、浮动
    css_02之盒模型、渐变
    javascript获取非行间样式的方法(可以兼容各个浏览器)
    gulp的用法
    grunt的用法
    grunt
    git用法
  • 原文地址:https://www.cnblogs.com/rookie123/p/14541400.html
Copyright © 2011-2022 走看看