If I have an array of values ['123', '456', '789'] what approach can I use to iterate over this array and replace, in matching sequence, parts of a string that have the value :id (for example users/:id/games/:id/server/:id)?
At the moment, I've been toying around with a .forEach(), but the initial value isn't getting updated per iteration. Curious how the following example could be altered in a way that would allow me to pass in an updated version of the string with one less :id on it.
goal:
input: { target: 'users/:id/games/:id/server/:id', ids: ['123', '456', '789'] }
output: 'users/123/games/456/server/789'
const injectPathVariables = (
target: string,
ids: string[]
): string => {
let newStr: string | undefined;
ids.forEach(id => {
if (newStr === undefined) {
newStr = target.replace(':id', id);
return;
}
newStr.replace(':id', id);
});
return newStr;
};