ECMAScript 2021 添加了新的 String 函数replaceAll
。
很久以前,在一个不远的星系里,人们使用split
+ join
或正则表达式替换所有出现的字符串 https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript.
我创建了以下示例来将新方法与旧方法进行比较。
虽然我可以在第一种情况下看到一些差异,例如我不能使用替换模式 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll#specifying_a_string_as_a_parameter with split
+ join
或者我需要转义特殊字符RegExp(str,"g")
,我看不出第二种情况有什么区别。
新方法和旧方法有什么区别(行为差异、性能、浏览器兼容性......)?
const source = "abcdefabcdef";
const str1 = "abc", str2 = "xyz";
const reg1 = /abc/g, reg2 = "xyz";
//Case 1 : When we want to replace a string by another
console.log(source.split(str1).join(str2));
console.log(source.replace(new RegExp(str1,"g"),str2));
//versus
console.log(source.replaceAll(str1,str2));
//Case 2 : When we want to use a regular expression
console.log(source.replace(reg1,reg2));
//versus
console.log(source.replaceAll(reg1,reg2));
//Result = "xyzdefxyzdef"
从搜集到的文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll for replaceAll
,我们发现以下花絮:
const newStr = str.replaceAll(regexp|substr, newSubstr|function)
注意:当使用regexp
你必须设置全局(“g”)标志;否则,它将抛出 TypeError:“replaceAll 必须使用全局 RegExp 调用”。
换句话说,当调用replaceAll
使用正则表达式文字或RegExp
,它必须使用全局标志。所以,打电话似乎没有多大收获replaceAll
与仅使用当前的replace
。然而,有一个区别是replaceAll
是当向它传递一个字符串时,它会自动进行全局替换。在这里,您可以节省一些打字时间,而不必输入全局标志。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)