3

I want to replace ":id" in url string with particular id e.g. 54 My question would be is it enough to use "/(:id)/i" for replacing this parameter, or I should use something more complex? Thanks

var url = "http://www.test.com/api/person/:id/details"
var str = url.replace(/(:id)/i, 54);

Updated:

I just realized that it would be great to have a function which would be able to replace multiple values in URL. Example:

function replaceParametersInUrl(url, params) {
  var regex = new RegExp(Object.keys(params).join('|'), 'gi');
    return url.replace(regex, function(matched) {
    return params[matched];
  });
}

console.log(replaceParametersInUrl("api/person/:userId/items/:itemId",  {userId: 56, itemId: 1}));

The problem with this solution is that it replaces just userId and itemId strings without ":". How I can achieve that it would replace those strings including ":"?

1
  • 1
    The one you have should be enough. You can also do away with the brackets since in this case you do not need what they provide. Thus /:id/ would be enough. Commented Dec 7, 2015 at 8:23

4 Answers 4

2

I wrote this function for solving the problem I mentioned in my updated question:

function replaceParametersInUrl(url, params) {
  var newObj = {};
  Object.keys(params).forEach(function(key) {
    newObj[':'+key] = params[key];
  });

  var regex = new RegExp(Object.keys(newObj).join('|'), 'gi');
  return url.replace(regex, function(matched) {
    return newObj[matched];
  });
}

console.log(replaceParametersInUrl("api/person/:userId/items/:itemId", {userId: 56, itemId: 1}));

Is it ok that I use ":" character in object keys?

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

Comments

1

In the "normal" case it should be enough. The user could type it :id or :Id but you already use the incasesensitive flag, so it should be fine.

But you are the one who should know if it is enough. Maybe there is a case in your application where there is an :id before the one you want to replace. Than you have a problem with the RegExp given above.

Comments

1

The code you have provided will work fine. Moreover,adding on to your code, braces not neede here (:id). Also, your regex will fail, if there is :id anywhere in the URL (although not expected, but developer should take care).

Modified code:

var url = "http://www.test.com/api/person/:id/details";
var str = url.replace(/\/:id\//i, '/54/');

Comments

0

Just another solution I came up with.

const replaceParametersInUrl = (url, params) =>
  url.replace(/:(\w+)/g, (match, group) => {
    if (!params[group]) throw new Error(`Unable to find value for ${match} param`);
    return `${params[group]}`;
  });

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.