3

I have the following link:

/v1/catalogue/folders/{catalogueId:[0-9]+}/translations/{translationId:[0-9]+}/

and the following data:

catalogueId: 31
translationId: 4

Now I'd like to change the part between the curly brackets with the value of the data-object. So the link needs to look like this:

/v1/catalogue/folders/31/translations/4/

Is there a way in Javascript to accoomplish this? If yes, what is that way?

1
  • When you made an attempt, what went wrong? I'd suggest taking a look at String.prototype.replace(), as a hint. But first, is that link in your browser's address bar (are you on the page that link represents), or is it a string somewhere else in your document? Commented Nov 15, 2016 at 15:51

2 Answers 2

2

This is one of the options:

const regex = /\{(.*?)\}/g
const url = "/v1/catalogue/folders/{catalogueId:[0-9]+}/translations/{translationId:[0-9]+}/"
const replacements = { catalogueId: 19, translationId: 20 } 

const result = url.replace(regex, function(_, segment) {
  return replacements[ segment.split(':')[0] ];
});
Sign up to request clarification or add additional context in comments.

1 Comment

Clean and concise. Edited to remove some of the parametric noise (sorry if it bothered)
1

see example below

var data = {
  catalogueId: 31,
  translationId: 4,
};

var url = $('#mylink').attr('href');
for(var key in data) {
  var regex = new RegExp('{' + key + '[^}]*}', 'g');
  console.log(regex);
  url = url.replace(regex, data[key]);
}
console.log(url);
$('#mylink').attr('href', url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="mylink" href="/v1/catalogue/folders/{catalogueId:[0-9]+}/translations/{translationId:[0-9]+}/">link</a>

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.