I've got the following function that takes in an object as well as a word and returns an object by replacing all occurrences of the passed word by another string. The same function will count the number of times the word has been replaced and will include that in the replaced string.
For example, consider the following:
let noOfReplacements = 0;
const reg = new RegExp(`\\bplease\\b`, "gi");
const data = [
{
name: "please, I said please",
title: "Test One",
more: [
{
name: "another name",
title: "please write something. I said please."
}
]
},
{ name: "testTwo", title: "Test Two" },
{ name: "testThree", title: "Test Three" },
{ name: "testFour", title: "Test Four" }
];
const replace = (obj, reg) => {
for (const key in obj) {
if (typeof obj[key] === "object" && obj[key] !== null) {
replace(obj[key], reg);
} else if (key === "title") {
obj[key] = obj[key].replace(reg, function () {
noOfReplacements += 1;
return `repalced${noOfReplacements}`;
});
}
}
return obj;
};
const result = replace(data, reg)
console.log("number of replacements", noOfReplacements);
console.log("result", result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
This works fine. However, I get an ESlint warning:
Function declared in a loop contains unsafe references to variable(s) 'noOfReplacements'
How can I safely update the noOfReplacements
in this case?
I have seen this example, but the problem with that solution is that it doesn't consider separate sentences and separately replaced words. So in the above example, while it will successfully replace all the words, it will only increase the count by 1 since both words are in the same property. Therefore, the noOfReplacements
remains at 1 when it should be 2.