Reputation: 287
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?
Upvotes: 3
Views: 1534
Reputation: 144689
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] ];
});
Upvotes: 2
Reputation: 2542
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>
Upvotes: 1