1

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;
};
1
  • What's your input, and expected output? You should add those to your question and try to create a minimal reproducible example. Commented Sep 5, 2021 at 22:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.