ITeye博客

javascript replaceAll 的实现

dh189 · 2010-07-16 10:59 · javascript · Web前端 · Markdown

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


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

测试方法如下:


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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。