-1

I have this string:

'/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'

I want to return only the id ('e78c7cfa-e469-4edd-8a87-9517a5b9e5da') after the last '/'. The id changes everytime I make an API call. How can I do that using any String functions?

Ani
  • 788
  • 3
  • 7
  • 21
  • 3
    `'/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'.split('/').slice(-1)` – 001 Nov 14 '22 at 14:03

3 Answers3

0

You could use match() here:

var input = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
var output = input.match(/[^\/]+$/)[0];
console.log(output);

Another regex option would be to do a replacement:

var input = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
var output = input.replace(/^.*\//, "");
console.log(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can use String.prototype.split which splits a string based on the given separator:

const path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'
const parts = path.split('/')
const id = parts[parts.length - 1] // the last chunk

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

m90
  • 11,434
  • 13
  • 62
  • 112
0

You can create a substring from the position of the last / (+ 1 to omit the it) to the end of the string:

str.slice(str.lastIndexOf('/') + 1)

Note: This assumes that the string will always contain a /. If it's possible that it doesn't you have to handle that case.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143