一、js中字符串的替换使用replace() 方法,但它只替换第一个匹配子串。如下例:
<script type="text/javascript"> var sourceString = "我是被替换的字符串,是被替换的哦"; var replaceString = sourceString.replace("替换", "replace"); alert(replaceString); // 我是被replace的字符串,是被替换的哦 </script>
可以看到替换后的replaceString的值为"我是被replace的字符串,是被替换的哦 ",replace(searchValue,replaceValue)方法替换的只是第一个匹配的字符串,那么如何实现替换全部匹配的字符串呢?——可以使用replace(searchRegexp,replaceValue)的正则表达式方式来实现。
<script type="text/javascript"> var sourceString = "我是被替换的字符串,是被替换的哦"; var replaceString = sourceString.replace(/替换/gm, "replace"); //sourceString.replace(new RegExp("替换", "gm"), "replace"); alert(replaceString); // 我是被replace的字符串,是被replace的哦 </script>
二、添加 Stirng对象的原型方法:实现replaceAll()方法
<script type="text/javascript"> // 替换所有 String.prototype.replaceAll = function (searchString, replaceString, ignoreCase) { if (RegExp.prototype.isPrototypeOf(searchString)) { return this.replace(searchString, replaceString); } else { return this.replace(new RegExp(searchString, (ignoreCase ? "gmi" : "gm")), replaceString); } } var sourceString = "我是被替换的字符串,是被替换的哦,Is Replace or replace?"; var replaceString = sourceString.replaceAll("替换", "replace"); //replaceString = sourceString.replaceAll(/替换/gm, "replace"); //replaceString = sourceString.replaceAll(new RegExp("替换", "gm"), "replace"); //replaceString = sourceString.replaceAll("replace", "替换"); // 我是被替换的字符串,是被替换的哦,Is Replace or 替换? //replaceString = sourceString.replaceAll("replace", "替换", true); // 我是被替换的字符串,是被替换的哦,Is 替换 or 替换? console.log(replaceString); alert(replaceString); // 我是被replace的字符串,是被replace的哦,Is Replace or replace? </script>