In the code that I develop and maintain I have ran into an issue.
I have a function that takes a query (type string) and replaces substrings of that string with a different string. As an example if a user types in the string I have a cat
it would replace it with I have a dog
.
My code works but the problem is I have hundreds of such substrings that need to be replaced with a different one. It also looks really bad aesthetically.
var myString;
myString = myString.replace('cat','dog')
.replace('elephant','zebra')
.replace('bird','fish')
// Goes on for hundreds of lines
This is all inside a function in which everytime it's called it goes through hundreds of replace
calls.
One thing I could try doing is creating an array of objects and iterating through it. The code would look something like this.
var animalsArray = [
{'a':'cat','b':'dog'},
{'a':'elephant','b':'zebra'},
{'a':'bird','b':'fish'}
];
And then in my 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']);
}
}
}
But I'm not sure whether that would improve on my current practice of chaining together hundreds of replace calls.
I'm basically looking to optimize my current code. What is the best practice?