替换 link Javascript 中的部分字符串

Replace part of string in a link Javascript

我有以下 link:

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

和以下数据:

catalogueId: 31
translationId: 4

现在我想用数据对象的值更改大括号之间的部分。所以 link 需要看起来像这样:

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

Javascript 有什么办法可以做到这一点吗?如果是,那是什么方式?

这是选项之一:

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] ];
});

参见下面的示例

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>