您的位置:首页 > 教程笔记 > 前端笔记

javascript模拟实现replaceAll()

2023-12-04 13:47:36 前端笔记 189

本章节分享一段代码实例,它模拟实现了replaceAll()方法功能。

代码实例:

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {   
  if (!RegExp.prototype.isPrototypeOf(reallyDo)) {   
    return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);   
  } 
  else {   
    return this.replace(reallyDo, replaceWith);   
  }   
}
var str="实例3";
console.log(str.replaceAll('o','a',true));

上面的代码实现了我们的替换效果,下面介绍一下它的实现过程。

一.代码注释:

(1).String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { },为String的圆形对象添加replaceAll()方法,第一个参数可以是正则表达式(用来匹配字符串中要被替换的内容),也可以是字符串中要被替换的内容,第二个参数规定使用什么内容进行替换,第三个参数规定是否忽略大小写。

(2).if (!RegExp.prototype.isPrototypeOf(reallyDo)),判断reallyDo是否是一个正则表达式对象。

(3).return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith),利用正则表达式进行替换操作。

(4).else {     return this.replace(reallyDo, replaceWith);   

},进行基本的替换操作。

(1).prototype可以参阅javascript prototype一章节。

(2).isPrototypeOf()方法可以参阅isPrototypeOf()一章节。

(3).replace()方法可以参阅正则表达式replace()一章节。

(4).RegExp()构造方法可以参阅正则表达式的创建一章节。

相关推荐