gpt4 book ai didi

javascript - JS 正则表达式抛出超出最大调用堆栈大小错误

转载 作者:行者123 更新时间:2023-12-05 02:40:43 24 4
gpt4 key购买 nike

我有一个很长的段落,我需要比较单词边界以用想要的值替换匹配。

想要的值(value)将有许多不同的模式。这就是为什么我需要有很多行新的 RegExp 来逐行替换。

var paragraph = "german gateway is located at ... Leonardo DA VINci and other some word superman";

paragraph
.replace( new RegExp("\\b"+ "german gateway" +"\\b", "ig"), "German gateway")
.replace( new RegExp("\\b"+ "Leonardo DA vinci" +"\\b", "ig"), "Leonardo da Vinci")
.replace( new RegExp("\\b"+ "some word" +"\\b", "ig"), "some other word")
.replace( new RegExp
//continue for at least Few Thousand Rows.

console.log(paragraph);

//示例输出

German gateway is located at ... Leonardo da Vinci and other some other word superman

但是新的RegExp太多导致js运行出错。

Uncaught RangeError: Maximum call stack size exceeded

有什么方法可以避免大量调用新的正则表达式,同时又能准确地维护我想要的正则表达式规则?

最佳答案

使用对象并迭代属性。如果您需要有保证的顺序,那么您可能希望使用一个对象数组,每次替换一个对象。

const paragraph = "german gateway is located at ... Leonardo DA VINci and other some word superman";

const replacements = {
"german gateway": "German gateway",
"Leonardo DA vinci": "Leonardo da Vinci",
"some word": "some other word"
/* ... */
};

const result = Object.entries(replacements)
.reduce((result, replacement) => {
const rx = new RegExp("\\b" + replacement[0] + "\\b", "ig");
return result.replace(rx, replacement[1]);
}, paragraph);

console.log(result);

而且您绝对应该转义传递给 RegExp() 构造函数的字符串中的可变部分。

关于javascript - JS 正则表达式抛出超出最大调用堆栈大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68393844/

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