gpt4 book ai didi

JavaScript字符串替换与replaceAll

转载 作者:行者123 更新时间:2023-12-04 04:30:21 24 4
gpt4 key购买 nike

ECMAScript 2021 添加了一个新的字符串函数 replaceAll .
很久以前,在一个不远的星系里,人们用split + join或正则表达式到 replace all occurences of a string .
我创建了以下示例以将新方法与旧方法进行比较。
虽然我可以在第一种情况下看到一些差异,例如我不能使用 replacement patternssplit + 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"

最佳答案

从收集 documentation对于 replaceAll ,我们发现以下花絮:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)


Note: When using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".


换句话说,当调用 replaceAll使用正则表达式或 RegExp ,它必须使用全局标志。因此,调用 replaceAll 似乎并没有什么收获。与仅使用当前的 replace 相比.但是,与 replaceAll 有一个区别。就是当给它传递一个字符串时,它会自动进行全局替换。通过不必输入全局标志,您可以在此处节省一些打字时间。

关于JavaScript字符串替换与replaceAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67296652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com