How to get value before last forward slash using Jquery

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!!


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


If your string will always be of that exact form (ie 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.

链接地址: http://www.djcxy.com/p/37760.html

上一篇: 使用拼接从数组中删除空值

下一篇: 如何在使用Jquery的最后一个正斜杠之前获取值