给出一系列网址
http://www.anydotcom.com/myfolder/some-url.html http://www.anydotcom.com/myfolder2/index.html# http://www.anydotcom.com/myfolder3/index.html?someParam=aValue http://www.anydotcom.com/foldername/index.html?someParam=anotherValue
首先,我如何从URL的末尾删除任何内容,以便最终得到
http://www.anydotcom.com/myfolder/some-url.html http://www.anydotcom.com/myfolder2/index.html http://www.anydotcom.com/myfolder3/index.html http://www.anydotcom.com/foldername/index.html
或者,理想情况下,我希望它返回
/myfolder/some-url.html /myfolder2/index.html /myfolder3/index.html /foldername/index.html
我试过
var thisUrl = "" + window.location; var myRegExp = new RegExp("([^(\?#)]*)"); thisUrl = myRegExp.exec(thisUrl);
但是会返回
http://www.anydotcom.com/foldername/index.html,http://www.anydotcom.com/foldername/index.html
我不太明白为什么。
我感谢你们的任何帮助!
答案 0 :(得分:2)
嗯,直接回答你的问题,这是正则表达式。
thisUrl = thisUrl.replace( /^https?:\/\/[^\/]|\?.*$/g, '' );
但是,由于您在代码中提到了window.location,因此您实际上可以直接从location object获取此数据。
thisUrl = top.location.pathname;
答案 1 :(得分:1)
如果您使用的是window.location
,则可以使用以下方式访问所需数据:
var thisUrl = window.location.pathname;
如果您要从链接中提取内容,以下正则表达式将为您提供所需内容:
// Supports all protocols (file, ftp, http, https, whatever)
var pathExtract = /^[a-z]+:\/\/\/?[^\/]+(\/[^?]*)/i;
var thisUrl = (pathExtract.exec(someUrl))[1];
答案 2 :(得分:0)
var loc = window.location;
var thisUrl = loc.protocol + "//" + loc.hostname + loc.pathname;
答案 3 :(得分:0)
使用对象window.location很简单,如:
function getPath() {
return window.location.pathname;
}