Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Regex throwing Maximum call stack size exceeded error

I have a very long paragraph that I need to compare word boundary to replace matching with the wanted value.

The wanted value will be in many many different patterns. This why I need to have a lot lines of new RegExp to go through the replacement one by one.

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);

//sample output

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

however too many new RegExp causing js to run into error.

Uncaught RangeError: Maximum call stack size exceeded

Is there any way to avoid heavily calling new RegExp while can maintaining exactly the regex rule that I want?

like image 978
i need help Avatar asked Jul 19 '26 03:07

i need help


1 Answers

Use an object and iterate over the properties. If you need a guaranteed order then you might want to use an array of objects with one object for every replacement.

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);

And you should definitely escape the variable part in the string you pass to the RegExp() constructor.

like image 198
Andreas Avatar answered Jul 20 '26 15:07

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!