手写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这里有四个数字
慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!