跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

javascript中使用replaceAll()函数实现字符替换的方法

而str.replace(/\-/g,"!")则可以全部替换掉匹配的字符(g为全局标志)。

replace()

The replace() method returns the string that results when you replace text matching its first argument

(a regular expression) with the text of the second argument (a string).

If the g (global) flag is not set in the regular expression declaration, this method replaces only the first

occurrence of the pattern. For example,

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

perform a global replace, finding and replacing every matching substring. For example,

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.replace(/reallyDo/g, replaceWith);

string.replace(new RegExp(reallyDo, 'g'), replaceWith);string:字符串表达式包含要替代的子字符串。

reallyDo:被搜索的子字符串。

replaceWith:用于替换的子字符串。

补充我们在Java中可以使用replaceAll()方法对字符串进行批量替换,但在JS中replaceAll()方法是undefined,JS中只存在replace()方法,因此我们可以自己封装JS中replaceAll()方法供我们便捷使用。

一、使用replace()方法进行替换

定义一个字符串:

var str = "hello world";使用replace()方法将字符串中的字母"l"替换成"i",原始做法: console.log(str.replace("l","i"));

输出:

“heilo world”

需要执行三次,非常不方便;

二、使用replaceAll()方法替换

封装replaceAll()方法:String.prototype.replaceAll = function(s1, s2) {return this.replace(new RegExp(s1, "gm"), s2);}

定义一个字符串:

var str = "hello world";使用replaceAll()方法进行批量替换:console.log(str.replaceAll("l", "i"));

输出:

“heiio worid”

只需要执行一次,就完成了全部替换需求。

总结一下, 四种方式

1. 使用具有全局标志g的正则表达式

var str = "dogdogdog";var str2 = str.replace(/dog/g,"cat");console.log(str2);实现替换全部匹配字符串,输出结果为:catcatcat

2. 使用另一种具有全局标志g的正则表达式

var str = "dogdogdog";var str2 = str.replace(new RegExp("dog","gm"),"cat");console.log(str2);输出结果同上例。这里g表示执行全局匹配,m表示执行多次匹配。

3. 给string对象添加原型方法replaceAll()

String.prototype.replaceAll = function(s1, s2) {return this.replace(new RegExp(s1, "gm"), s2);}这样就可以像使用replace方法一样使用replaceAll方法:var str = "dogdogdog";var str2 = str.replaceAll("dog", "cat");console.log(str2);输出结果同上例。

4. 使用先split,再join的方法

评论区@默默之分享的这个方法太赞了,拉到正文里以免有人不看评论,感谢@默默之分享。

var str = "dogdogdog";var str2 = str.split("dog").join("cat") console.log(str2);输出结果同上例。

您可能感兴趣的文章:Javascript中正则表达式的全局匹配模式分析Javascript中使用exec进行正则表达式全局匹配时的注意事项JavaScript实现的字符串replaceAll函数代码分享javascript实现全局匹配并替换的方法java中replaceAll替换圆括号实例代码Java中replace与replaceAll的区别与测试java字符串的替换replace、replaceAll、replaceFirst的区别说明Java replaceAll()方法报错Illegal group reference的解决办法String.replaceAll方法详析(正则妙用)浅谈Java中replace与replaceAll区别Java中replace、replaceAll和replaceFirst函数的用法小结浅谈java中replace()和replaceAll()的区别jQuery中replaceAll()方法用法实例js使用正则实现ReplaceAll全部替换的方法js字符串替换所有的指定字符或文字(推荐replaceAll方法) JS中实现replaceAll的方法(实例代码) js replace 与replaceall实例用法详解Flex 字符串ReplaceAll使用说明JavaScript中使用replace结合正则实现replaceAll的效果

相关文章