How to get value before last forward slash using Jquery
I ha got these types of hrefs
http://localhost:8080/en/reservations/t开发者_StackOverflowours-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 (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.
精彩评论