javascript replace()实现多次替换的方法
定义和用法
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
语法
stringObject.replace(regexp/substr,replacement)参数 描述
regexp/substr 必需。规定子字符串或要替换的模式的 RegExp 对象。
请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。
replacement 必需。一个字符串值。规定了替换文本或生成替换文本的函数。
返回值
一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。
示例
下面的示例演示了 replace 方法将第一次出现的单词 "The" 替换为单词 "A" 的用法。
代码如下 | |
function ReplaceDemo(){ var r, re; // 声明变量。 var ss = "The man hit the ball with the bat.n"; ss += "while the fielder caught the ball with the glove."; re = /The/g; // 创建正则表达式模式。 r = ss.replace(re, "A"); // 用 "A" 替换 "The"。 return(r); // 返回替换后的字符串。 } |
更多详细内容请查看:http://www.111cn.net/wy/99/js_replace_replaceall.htm
上面的只能替换一次,下面我们来看看实现多次替换的方法
代码如下 | |
<script language="javascript"> |