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?
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] ];
});
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.