replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
stringObject.replace(regexp,replacement)
说明
字符串 stringObject 的 replace() 方法执行的是查找并替换的操作。它将在 stringObject 中查找与 regexp 相匹配的子字符串,然后用 replacement 来替换这些子串。如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。
replacement 可以是字符串,也可以是函数。如果它是字符串,那么没有匹配都将由字符串替换。但是replacement 中的 $字符具有特定的含义。如下表所示,它说明从模式匹配得到的字符串将用于替换。 字符替换文本 $1、$2、…、$99与regexp 中的第 1 到第 99 个子表达式相匹配的文本。$&与 regexp 相匹配的子串。$` 位于匹配子串左侧的文本。$’ 位于匹配子串右侧的文本。%直接量符号。
使用 “W3School” 替换字符串中的 “Microsoft”:
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
</script>
执行一次全局替换,每当 “Microsoft” 被找到,它就被替换为 “W3School”:
<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
</script>
确保匹配字符串大写字符的正确:
text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");
把 “Doe, John” 转换为 “John Doe” 的形式:
name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");
将把所有的花引号替换为直引号:
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");
把字符串中所有单词的首字母都转换为大写:
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);
代码如下:
var str="fsaf$a$assdfdasfa$a$dsfadsf";
var strr='\$'+'a'+'\$';
var name = '"a", "b"';
var reger=new RegExp("[\$]a[\$]","gm");
alert(str.replace(reger,'555888'));