6

I ha got these types of hrefs

http://localhost:8080/en/reservations/tours-and-safaris-booking-enquiry-form/dubai/index.aspx
http://localhost:8080/en/reservations/tours-and-safaris-booking-enquiry-form/muscat/index.aspx

Now I need to write a function which will take this as input and will return "tours-and-safaris-booking-enquiry-form".

Please suggest!!

Manoj Singh
  • 7,569
  • 34
  • 119
  • 198
  • 1
    [This answer](http://stackoverflow.com/questions/651563/get-the-last-element-of-a-splitted-string-array-in-javascript) should answer your question; however, split the string using a slash instead of a comma. – Labu Sep 29 '11 at 10:38

2 Answers2

8

You can do a rudimentary split (to an array) and get the second-to-the-last element.

var _array = url.split('/'),
    _foo = _array[_array.length-2];

You have to watch out for URLs formatted this way:

http://your.domain.com/path/to/something/

... that is, those with trailing forward slashes, as those will create an empty array element at the end (which can throw off your parsing). You may want to sanitize your array first by removing empty elements before retrieving the particular string you really want (using something like this solution).

Community
  • 1
  • 1
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
3

If your string will always be of that exact form (i.e. always have the same number of / characters before the part you want) then you can do this:

var partYouWant = yourString.split("/")[5];

split does what it says, and splits the string, using the specified string as a delimiter (in this case, it uses the / character as the delimiter). That returns an array, and the part you want is at index 5.

Note that jQuery will not help you in the slightest here. It's plain old JavaScript that you want.

James Allardice
  • 164,175
  • 21
  • 332
  • 312