kevin
kevin

Reputation: 3528

how to use an array to replace parts of a string

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;
};

Upvotes: 1

Views: 140

Answers (2)

Riza Khan
Riza Khan

Reputation: 3158

let string = "users/:id/games/:id/server/:id";
const arr = ["123", "456", "789"];
arr.forEach((i) => {
  string = string.replace(":id", i);
});

console.log(string);

Here it is in action.

Upvotes: 2

Ahmed Essam ElDessouki
Ahmed Essam ElDessouki

Reputation: 1131

Array.forEach() irritates the array.

Array.map() irritates the array and returns a new array.

const injectPathVariables = (
  target: string,
  ids: string[]
): string => {
  let newStr: string | undefined;
  ids.map(id => {
    if (newStr === undefined) {
      newStr = target.replace(':id', id);
      return; // this will result in replacing id with Undefined 
    }
    newStr.replace(':id', id);
  });
  return newStr;
};

Upvotes: 0

Related Questions