梦100幽灵船:javascript下如何将多个连续相同字符替换成一个字符

来源:百度文库 编辑:高考问答 时间:2024/04/29 06:53:16
比如说:var string1="abacd cdfed efae adsdf"
请注意其中有多个空格。
将" "替换成"|"
替换之后成为string1="abacd|cdfed|efae|adsdf"
把string1改为=="abacd.....cdfed....efae.....adsdf",把"."改为"|",其它条件一样,2楼那位兄弟没有全部答对问题。
可是string1中"......"长度是不一致的。不一定都是6个,如"....",
或者说就是如何判断遇到的在每一串"...."遇到的是第一个"."要改为"|",其它的要删除。
先谢谢2楼那位兄弟。

如果不是定长,可以先判断最长的是多少,而后逐一替换。

回答补充:把" "改为"."

var string1="abacd......cdfed......efae......adsdf";
while(string1.indexOf(".")>0){//注释当字符串中有空格循环执行
string1=string1.replace(".","|");
}
document.write(string1);

结果是:abacd||||||cdfed||||||efae||||||adsdf

var string1="abacd......cdfed......efae......adsdf";
while(string1.indexOf("......")>0){//注释当字符串中有空格循环执行
string1=string1.replace("......","|");
}
document.write(string1);

结果是: abacd|cdfed|efae|adsdf

replace(" ","|")替换第一个空格!

配合indexOf(" ")一起使用!

var string1="abacd cdfed efae adsdf";
while(string1.indexOf(" ")>0){//注释当字符串中有空格循环执行
string1=string1.replace(" ","|");
}
document.write(string1);