伴娘拦门流程:JAVASCRIP的replace方法

来源:百度文库 编辑:高考问答 时间:2024/04/29 05:05:46
JAVASCRIP里面的replace 方法,为什么只能替换第一个字符呢?比如说我想把“afagagat”中的“a”都替换成“b“,为什么他只替换第一个a,其他的就不管了呢?

js得replace确实只替换第一个找到得要替换得,后面不管。
给你一个函数:
function replaceAll(text,replacement,target){
if(text==null || text=="") return text;//如果text无内容,返回text
if(replacement==null || replacement=="") return text;//如果replacement无内容,返回text
if(target==null) target="";//如果target无内容,设置为空串
var returnString="";//定义返回值变量,并初始化
var index=text.indexOf(replacement);//定义查找replacement的索引下标,并进行第一次查找
while(index!=-1)
{//直至未找到replacement,要么进行下面的处理
alert(index);
alert(returnString);
returnString+=text.substring(0,index)+target;//如果找到的replacement前有字符,累加到返回值中,并加上target
text=text.substring(index+replacement.length);//取掉找到的replacement及前边的字符
index=text.indexOf(replacement);//进行查询,准备下一次处理
}
if(text!="") returnString+=text;//如果找到的最后一个replacement后有字符,累加到返回值中
return returnString;//返回
}
比如你上面得代码为:
replaceAll("afagagat","a","b");