1

I have a object like this:

let data = {
    url: "https://test.ir/apps/:type/:id/",
    params: {
        id: "com.farsitel.bazaar",
        type: "xyz",
    },
    query: {
        ref: "direct",
        l: "en",
    },
};

I want to replace :type and :id in url with equivalent key to each from params object. what is the best solution in javascript?

2 Answers 2

2

Solution based on matching keys from params to the value of a regular expression from key url, followed by an update of that key.

On input: https://test.ir/apps/:type/:id/

On output: https://test.ir/apps/xyz/com.farsitel.bazaar/

let data = {
    url: "https://test.ir/apps/:type/:id/",
    params: {
        id: "com.farsitel.bazaar",
        type: "xyz",
    },
    query: {
        ref: "direct",
        l: "en",
    },
};

let new_url = data.url.replace(/:(\w+)/g, (match, key) => data.params[key] || match);

data.url = new_url;

console.log(data);

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

1 Comment

Thanks body. that's a good solution. I have always some problems with understanding regex phrases :)
0

Could you just use String.replace?

const data = {
   url: "https://test.ir/apps/:type/:id/",
   params: {
      id: "com.farsitel.bazaar",
      type: "xyz",
   },
   query: {
      ref: "direct",
      l: "en",
   },
}

const url = data.url.replace(":type", data.params.type).replace(":id", data.params.id);

console.log(url)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.