JavaScript中String的replace函数

1.replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

语法:stringObject.replace(regexp/substr,replacement)

例子:

1 "I'm Demon".replace("D","d") // I'm demon
View Code

上面和我们想的一样,但

1 "I'm a student, and you?".replace("n","N"); // I'm a studeNt, and you?
View Code

为什么会这样呢?

第二个‘n’没有被替换。字符串的 replace 方法如果第一个参数传入字符串,那么只有第一个匹配项会被替换。如果要替换全部匹配项,需要传入一个 RegExp 对象并指定其 global 属性。

正确的应该为

1 "I'm a student, and you?".replace(/n/g,"N"); // I'm a studeNt, aNd you?
View Code
原文地址:https://www.cnblogs.com/sxmcACM/p/3982837.html