使用RegExp从URL提取ID

时间:2018-10-27 23:00:28

标签: regex typescript

我有这种网址: /clients/18378/offers/2219/items/32779

我正在尝试在其中添加一个数组:18378221932779

我尝试过此代码,但未成功:

let currentUrl = this.router.url; // = '/clients/18378/offers/2219/items/32779'
var regexRouteOffer = /\/clients\/(.*?)\/offers\/(.*?)\/items\/(.*?)/gm;
var match = currentUrl.match(regexArticleInOffer);
console.log("Test 1 >>", match); // => ["/clients/18378/offers/2219/items/"]

我尝试使用exec函数,但是它只给我一个数字(仅第一个)

var matches = [];
for (var m = null; m = regexRouteOffer.exec(currentUrl); matches.push(m[1]));
console.log("Test 2 >> ", matches); //["18378"]

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您不需要标志g(因为只想匹配一次)和m(因为不需要打开多行模式)。最后,最后一个.*是不贪心的,因此它尝试匹配尽可能少的元素(在这种情况下为零),因此请删除全部或至少最后一个?

let currentUrl = '/clients/18378/offers/2219/items/32779'
var regexRouteOffer = /\/clients\/(.*)\/offers\/(.*)\/items\/(.*)/;
var match = currentUrl.match(regexRouteOffer);
console.log(match[1]); // 18378
console.log(match[2]); // 2219
console.log(match[3]); // 32779