---
title: "重写replace方法"
author: "lcb530"
date: "2010-06-18T15:48:56Z"
tags: ["JavaScript", "prototype"]
categories: ["Web前端"]
slug: "replace"
draft: false
lastmod: "2010-06-18T15:48:56Z"
id: 694006
url: "https://lcb530.iteye.com/blog/694006"
---

js中replace函数，只能替换从第一个字符开始，符合要求的字符串，它不能做到替换多个符合要求的字符串，例："a1a2a3a4".replace('a',''),他的替换结果等于：1a2a3a4,要想替换所有的a，使替换结果等于：1234，则可以重写replace方法。

<span style="color:red">代码如下：</span>

```javascript
String.prototype.replaceAll  = function(s1,s2){    
     return this.replace(new RegExp(s1,&quot;gm&quot;),s2);    
} 
```