Matt Elhotiby
Matt Elhotiby

Reputation: 44086

Parsing a string with Jquery or Javascript

How do i pull out the 30 or the 55 basically the number before the last number

http://something.com:9090/general/35/30/205
http://something.com:9090/general/3/55/27
http://something.com:9090/general/36/30/277

Upvotes: 1

Views: 1280

Answers (4)

MooGoo
MooGoo

Reputation: 48270

var parts = url.split('/');

var i = parts.length, num;
while (--i)  
  if (!isNaN(parts[i]) && !isNaN(parts[i+1])) {
    num = parts[i];
    break;
  }

Without regex, and somewhat like Mike Ruhlin's solution, but more specific to the "number before the last number" part of your question.

Upvotes: 0

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

var url = "http://something.com:9090/general/35/30/205";
var splits = url.split('/');
return splits[splits.length - 2];

This will screw up if your url looks like: "http://something.com:9090/general/35/30/205/" but you could always trim off the trailing slashes beforehand.

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 238075

You need to use regular expressions for this. As a brief example, here you need to do the following:

var url = "http://something.com:9090/general/35/30/205";
var category = url.match(/(\d+)\/\d+$/)[1];

To parse the regular expression:

  • / start the regular expression
  • (\d+) create a group that you want to find the value of later. This group must contain 1 or more number characters
  • \/ next must come a forward slash. The backslash "escapes" the forward slash -- otherwise it would end the regular expression
  • \d+ next must come 1 or more number characters
  • $ this must be the end of the string
  • / end the regular expression.

The match function returns an array of items that we selected -- here, just (\d+). The [1] means "get the first match", which will be 30 in the above string.

Upvotes: 2

user372551
user372551

Reputation:

var s = "http://something.com:9090/general/35/30/205";
s.substr(s.lastIndexOf('/') - 2,2);

Upvotes: 1

Related Questions