javascript模拟实现replaceAll()

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它模拟实现了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="pipipi.net";
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()构造方法可以参阅正则表达式的创建一章节。

一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu

回复

我来回复
  • 暂无回复内容