0

Having a string such like this one:

var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";

I need to be able to only get "6579" number from that string, because it is an ID I need to use. In fact, this ID is always located between that last "/" and the next "-" that follows.

So considering that the url is dynamic but this "ID" is always between these two characters "/" and "-", I have to be able to always get the ID.

Any Idea how could I solve this?

I tried with this but

var id = str.lastIndexOf('/');
Taplar
  • 24,788
  • 4
  • 22
  • 35
victoriana
  • 69
  • 5
  • Does this answer your question? [Get Substring between two characters using javascript](https://stackoverflow.com/questions/14867835/get-substring-between-two-characters-using-javascript) – Heretic Monkey Feb 18 '20 at 19:52

3 Answers3

3

You can use a regular expression to match digits, followed by a dash and making sure anything after it is not a slash.

var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";
console.log(str.match(/\/(\d+)-[^/]+$/)[1])
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

If you do not want to use a regexp.

'"https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva"'
  .split('/').pop()
  .split('-').shift();

pop() removes the last element.

shift() removes the first element.

Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Love the `.pop` and `.shift` approach, never seen that before for a regex lookbehind/lookahead substitute! +1 – Lewis Feb 18 '20 at 19:53
0

Take your var id and substr your original String

var index = str.lastIndexOf('/');
var id = str.substr(index+1,4);
jomoji
  • 5
  • 5