victoriana
victoriana

Reputation: 69

how to get specific characters between others in a string with jquery?

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('/');

Upvotes: 0

Views: 428

Answers (3)

jomoji
jomoji

Reputation: 5

Take your var id and substr your original String

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

Upvotes: 0

epascarello
epascarello

Reputation: 207511

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])

Upvotes: 3

Taplar
Taplar

Reputation: 24965

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.

Upvotes: 1

Related Questions