---
title: "javascript replaceAll 的实现"
author: "dh189"
date: "2010-07-16T10:59:46Z"
tags: []
categories: ["Web前端"]
slug: "javascript-replaceall"
draft: false
lastmod: "2010-07-16T11:03:27Z"
id: 714184
url: "https://dh189.iteye.com/blog/714184"
---

javascript 默认只有replace方法，而且只能替换一次，要想实现java中的replaceAll的功能就要对JavaScript的字符串进行方法拓展，代码如下：

```java

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);
	    }
}

```

测试方法如下：

```java

function test(){
	var s="我的青春我做主！";
	alert(s.replaceAll("我","你"));
}
test();

```