I have an array of values like ['123', '456', '789']. What is the best way to iterate over this array and update parts of a string that contain the text :id in sequence (e.g. users/:id/games/:id/server/:id)?
Currently, I've been experimenting with using .forEach(), but the original value isn't changing with each iteration. I'm interested in how I can modify the following example to allow me to provide an updated version of the string with one less occurrence of :id.
Objective:
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;
};