开发者

javascript, how to get url path?

I wanna get url path by javascript,

for example, i have these urls:

http://localhost:8080/blah/blah/index.php?p=1开发者_开发技巧

http://localhost:8080/blah/blah/index.php

http://localhost:8080/blah/blah/

http://localhost:8080/blah/blah

and i would like to get: http://localhost:8080/blah/blah/ anyone please help me


This appears to be an ambigious problem with no definitive solution because there is no concrete definition of what you want removed from the end of the URL.

It would be easy to remove the query parameters (first example).

It would be easy to normalize the trailing slash (last two examples).

It would be easy to remove the last piece of the path if that is what you always wanted, but unless you're willing to add some more rules that can distinguish /index.php from /blah at the end of the URL so that an algorithm knows when to remove one, but not the other, what you have asked for is not possible. As you have defined the problem, the code cannot know whether the blah at the end of http://localhost:8080/blah/blah should be removed or not.

For example, this code will remove the query parameters and the last piece of the URL, but that will only work on the three of the four examples, but runs into the ambiguity about what you want removed at the end:

function cleanURL(url) {
    return(url.replace(/\?.*$/, "").replace(/\/[^\/]*$/, "") + "/");
}

And here it is being run on all four of your examples: http://jsfiddle.net/jfriend00/2Q4Ue/. It returns these results for the four cases:

http://localhost:8080/blah/blah/
http://localhost:8080/blah/blah/
http://localhost:8080/blah/blah/
http://localhost:8080/blah/

For the last URL, you can see that the algorithm identified /blah at the end as the filename and removed it since there is no way to know if that's part of the path or a filename.

If you were willing to make a new rule that the filename must have a file extension and the last piece of the pathname when there is no filename will never have an extension, then such an algorithm could be written to handle the last case.

OK, with a new rule that a filename at the end is anything with a period in it, then, you can use this:

function cleanURL(url) {
    return(url.replace(/\?.*$/, "")
           .replace(/\/[^\/]*\.[^\/]*$/, "")
           .replace(/\/$/, "") + "/");
}

Which is shown in this fiddle: http://jsfiddle.net/jfriend00/LpauM/ and produces this result for the four test URLs:

http://localhost:8080/blah/blah/
http://localhost:8080/blah/blah/
http://localhost:8080/blah/blah/
http://localhost:8080/blah/blah/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜