开发者

How to get part of the path with jQuery?

开发者 https://www.devze.com 2023-03-17 18:27 出处:网络
I have following URL www.webiste.com/Services/allservices.html How could I get part of this URL with jQuery?

I have following URL www.webiste.com/Services/allservices.html

How could I get part of this URL with jQuery?

e.g开发者_如何学运维 'services' or 'allservices.html'

Any suggestion much appreciated.


var url = "www.webiste.com/Services/allservices.html"
    url = url.split("/");
    alert(url[1]);

In the above example split the string url when find / (separator) and save it in an array. Then using the proper index, you can use the substring you wish (in the above example will alert Services).

Demo: http://jsfiddle.net/jcNSs/

More info for split() : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split


var url = 'http://www.website.com/Services/allservices.html';

// Getting the file name (allservices.html)
var fn = url.split('/').reverse()[0];

// Getting the extension (html)
var ext = url.split('/').reverse()[0].split('.').reverse()[0];

// Getting the last middle part (services)
var lm = url.split('/').reverse()[1];


If you are using the JavaScript window.location you can split location.pathname using '/' and use pop() to get the last element or get by index:

var splitUrlArray = urlString.split('/'); 
var lastPart = splitUrlArray.pop();
var firstPart = splitUrlArray[0]; 

Read http://davidwalsh.name/javascript-window-location for more details on the window.location.


Split it by "/" and then choose the last element.

var parts = $("selectorForText").val().split("/");
//parts[0] = www.website.com
//parts[1] = Services
//parts[2] = allservices.html

Something to that effect will work - the important bits being the split() function and the recognition that it returns an array of strings

--Edited to provide example--


This isn't a jQuery problem as there are a couple of javascript functions that can help you (obviously it'll still work in and around jQuery). The easiest way is to just split on the path separator and then manipulate it however you like:

a = "www.website.com/Services/allservices.html".split("/")

 => ["www.website.com", "Services", "allservices.html"]

Then you can piece it together however you like:

  • Host

    a.slice(0) => "www.website.com"

  • Path

    a.slice(1, a.size()) => ["Services", "allservices.html"] a.slice(1, a.size()).join("/") => "Services/allservices.html"

etc.

Enjoy :-)


Another simpler way:

urlParts = "www.website.com/About/subpage1.html".split("/")
    var Part1= urlParts[1]+"/";   // e.g. About/
    var Part2 = urlParts[2];      // e.g. subpage1.html
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号