Get a number from a string from end to dash

Viewed 65

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

1 Answers

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);
Related