JS 字符串有replace() 方法。但这个方法只会对匹配到的第一个字串替换。 如下例:
[javascript] view plaincopyprint?
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<script>
var str = "wordwordwordword";
var strNew = str.replace("word","Excel");
alert(strNew);
</script>
</BODY>
</HTML>
<HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <script> var str = "wordwordwordword"; var strNew = str.replace("word","Excel"); alert(strNew); </script> </BODY> </HTML>
如果要全部替换的话,JS 没有提供replaceAll这样的方法。使用正则表可以达成Replace 的效果:
[javascript] view plaincopyprint?
str.replace(/word/g,"Excel")
str.replace(/word/g,"Excel")
g 的意义是:执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
[javascript] view plaincopyprint?
<HEAD>
<TITLE> New Document </TITLE>
<script>
function replaceAll(str)
{
if(str!=null)
str = str.replace(/word/g,"Excel")
return str;
}
</script>
</HEAD>
<BODY>
<script>
var str = "wordwordwordword";
var strNew = str.replace("word","Excel");
strNew = replaceAll(str);
alert(strNew);
</script>
</BODY>
</HTML>
<HEAD> <TITLE> New Document </TITLE> <script> function replaceAll(str) { if(str!=null) str = str.replace(/word/g,"Excel") return str; } </script> </HEAD> <BODY> <script> var str = "wordwordwordword"; var strNew = str.replace("word","Excel"); strNew = replaceAll(str); alert(strNew); </script> </BODY> </HTML>
以上写法有个类同的写法:
[javascript] view plaincopyprint?
str.replace(new RegExp("word","gm"),"Excel")
str.replace(new RegExp("word","gm"),"Excel")
g | 执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。 |
m | 执行多行匹配。 |
[javascript] view plaincopyprint?
除此之外,也可以添加 Stirng对象的原型方法:
[javascript] view plaincopyprint?
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
String.prototype.replaceAll = function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); }
这样就可以像使用replace 方法一样使用replaceAll了
[javascript] view plaincopyprint?
str.replaceAll("word","Excel");
str.replaceAll("word","Excel");
总结一下, 三种方式
1. str.replace(/oldString/g,newString)
2. str.replace(new RegExp(oldString,"gm"),newString)
3. 增加String 对象原型方法 replaceAll
js 实现ReplaceAll 的方法 .,布布扣,bubuko.com
原文地址:http://1030967291.blog.51cto.com/6293718/1543092