JS中实现replaceAll的方法(实例代码) |
本文标签:JS,replaceAll方法 第一次发现JavaScript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符. replace() var s = "Hello. Regexps are fun.";s = s.replace(/\./, "!"); // replace first period with an exclamation pointalert(s); produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to var s = "Hello. Regexps are fun.";s = s.replace(/\./g, "!"); // replace all periods with exclamation pointsalert(s); yields this result: “Hello! Regexps are fun!” 所以可以用以下几种方式.: string:字符串表达式包含要替代的子字符串 。 复制代码 代码如下: <script type="text/javascript"> String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.isPrototypeOf(reallyDo)) { return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); } else { return this.replace(reallyDo, replaceWith); } } </script> |