I'm retrieving data via an api on football. There are some mistakes written in the data that needs to be adjusted. What I wanna know is, if it is possible to write a single piece of code that does the job instead of repeating an if/else statement multiple times as shown below. Thank you.
// So replace the strings in the includes methods in one execution
if( el.team.name.includes("Rotterdam")){
el.team.name = el.team.name.replace("Rotterdam", "");
}
if(el.team.name.includes("'65")){
el.team.name = el.team.name.replace("'65", "");
}
if(el.team.name.includes("Almelo")){
el.team.name = el.team.name.replace("Almelo", "");
}
Alternate between all possible strings you want to remove with a regular expression, then perform a global replacement with the empty string:
el.team.name = el.team.name.replace(/Rotterdam|65|Alemo/g, '');
Side note - even with your original code, there's no need to test whether the substring is included first. If .replace
finds no matches, nothing will be replaced, so the following code would work too (though the regex is preferable):
el.team.name = el.team.name.replace("Rotterdam", "");
el.team.name = el.team.name.replace("'65", "");
el.team.name = el.team.name.replace("Almelo", "");
as would calling .replace
on the result of the last .replace
:
el.team.name = el.team.name
.replace("Rotterdam", "")
.replace("'65", "")
.replace("Almelo", "");
(the above can be a good strategy when a single regular expression would be too hard to read, or when you have different strings to insert when a match is found)