2

I have URL and i need to get the id, which is at the end of the string. The URL is looking this /questions/M%C3%A4rkte+que+sentra-361433. I need to get the last number to the dash. I am trying to use this expression but it grabs all numbers.

let str = 'questions/M%C3%A4rkte+que+sentra-361433';
let id = str.replace(/[^0-9]/g,'');

In this concrete example, I got 34361433, but it should be 361433

Sasha Zoria
  • 739
  • 1
  • 9
  • 28

1 Answers1

2

Using Regex:

let str = 'questions/M%C3%A4rkte+que+sentra-361433';
let id = str.match(/(?:-)(\d+)$/)[1];
console.log(id);

As another way without Regex, if it is applicable to you:

let str = 'questions/M%C3%A4rkte+que+sentra-361433';
let splitted = str.split('-');
let id = splitted[splitted.length - 1];
console.log(id);
StepUp
  • 36,391
  • 15
  • 88
  • 148