While working on the code I develop and maintain, I encountered an issue.
There is a function in my code that takes a query (in the form of a string) and replaces certain substrings within that string with different ones. For instance, if a user inputs the string I have a cat
, it should replace it with I have a dog
.
The current implementation works fine, but the problem is that there are hundreds of such substrings that need to be replaced, making the code look messy aesthetically.
var myString;
myString = myString.replace('cat','dog')
.replace('elephant','zebra')
.replace('bird','fish')
// This goes on for many lines
All these replace operations are nested inside a function that has to go through all the replacements every time it's called.
One approach I am considering is creating an array of objects and iterating through it to perform the replacements. Here's how the code would change:
var animalsArray = [
{'a':'cat','b':'dog'},
{'a':'elephant','b':'zebra'},
{'a':'bird','b':'fish'}
];
And then in the function:
function stringReplace(string) {
for (var i = 0; i < animalsArray.length; i++) {
if (string.indexOf(animalsArray[i]['a']) > -1) {
sting = string.replace(animalsArray[i]['a'],animalsArray[i]['b']);
}
}
}
However, I'm unsure if this approach would actually enhance the performance compared to chaining together hundreds of replace calls as currently implemented.
In essence, I'm seeking ways to optimize my existing code. What would be the best practice in this scenario?