79449223

Date: 2025-02-18 18:07:49
Score: 1.5
Natty:
Report link

An alternative could be a regex pattern, but this is as brittle as any solution that assumes URL structures will never change. Relying on URLs for the id is probably not the most solid approach. Surely the JSON stream holds the actual ids somewhere, at least indirectly in the linked objects?

Explanation of the matching pattern /\/(\d+)\/?$/ used in the example below:

  1. \/ matches a forward slash, escaped with a backslash.
  2. (\d+) gets one + more digits
  3. \/? gets optional /, escaping it.
  4. $ matches end of string
  5. The first and last / are JS regex delimiters, so not functional parts o the patten

Most of this is touched upon in the Regular expressions at MDN. Also see String.prototype.match() for this method.

const url = 'https://jsonplaceholder.typicode.com/todos/101/';
const idInUrlPattern = /\/(\d+)\/?$/;
//? handles a null case, [1] returns the matching group
const getIdFromUrl = url => url.match(idInUrlPattern)?.[1];
console.log(getIdFromUrl(url));

Reasons:
  • Blacklisted phrase (1.5): any solution
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: MiB