语法
stringObject.replace(regexp/substr,replacement)
replace
用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。
代码如下 | 复制代码 |
var result1 = a.replace(re,"Hello"); //result1 = "Hello" var result2 = b.replace(re,"Hello"); //result2 = ",world" |
例1
代码如下 | 复制代码 |
<script language="javascript"> var strM = "javascript is a good script language"; //在此我想将字母a替换成字母A alert(strM.replace("a","A")); </script> |
上面的替换只是简单的,我们上面讲了replace可以用正则匹配替换的
例2
代码如下 | 复制代码 |
<script language="javascript"> var strM = "javascript is a good script language"; //在此将字母a全部替换成字母A alert(strM.replace(/a/g,"A")); </script> |
替换所有要替换字符
//将字母i全部替换成5
代码如下 | 复制代码 |
<script language="javascript"> var txt = "sjfisjfisdjfijsidfjioalfjewofjjgs"; alert(txt .replace(/i/g,"5")); </script> //只将第一个字母i替换成5 <script language="javascript"> |
时间: 2024-08-30 22:33:09