I'm having trouble while using javascript replace() method, I've created a codesandbox to describe my issue briefly. Here is the Link to Codesandbox
As you can see I'm calculating the string of codes, where each codes will be replaced by its respective value using replace method & string will be calculated using eval().
Here the issue is I'm not getting the correct calculation because of first codes replaced value contains another code "2405" in it, so replace method replacing the value of the first code with "2405" codes value & actual code "2405" in the string is not getting replaced by its respective value. how should I handle this case, Any suggestion of a new method will be appreciable, thanks!
CodePudding user response:
use a regular expression with the replace() method to replace all occurrences of the codes in your string.
const regex = new RegExp(ResultantJSON.map((item) => item.account).join("|"), "g");
CodePudding user response:
use a replaceAll() javascript method to solve your code.
const p = 'Hello!! StackOverFlow Developers.';
console.log(p.replaceAll('Developers', 'Designers'));
const regex = /Developers/evelop;
console.log(p.replaceAll(regex, 'esign'))