Javascript 拆分 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18254699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Split URL
提问by 33_____________
I want to SPLIT some specific parts of the URL, here is what i have so far.
我想拆分 URL 的某些特定部分,这是我目前所拥有的。
<script type='text/javascript'>
var query = window.location.pathname.split( '/' );
query = window.location.pathname.split( '.html' );
var redirectpath = "http://www.mydomain.com/search/?q="
window.location.href = redirectpath + query;
</script>
The URL structure will be like this:
URL 结构将是这样的:
http://www.mydomain.com/page/2013/05/some-page-title.html
The variable query
outputs like this;
page,2013,05,some-page-title
变量query
输出是这样的;
page,2013,05,some-page-title
i only want the some-page-title
part and also remove the hyphens.
我只想要这some-page-title
部分并删除连字符。
so the final output would be http://www.mydomain.com/search/?q=some page title
所以最终的输出将是 http://www.mydomain.com/search/?q=some page title
how is that possible? Please help!! Thanks
这怎么可能?请帮忙!!谢谢
回答by Rene Pot
Split returns an array, use it as an array!
拆分返回一个数组,将其用作数组!
var parts = window.location.pathname.split( '/' );
var query = parts[parts.length-1].split( '.html' );
query[0]= query[0].replace(/-/g," ");
var redirectpath = "http://www.mydomain.com/search/?q="
window.location.href = redirectpath + query[0];
This assuming you always want the part of the url after the last /
这假设您总是想要最后一个之后的 url 部分 /
回答by jaskirat Singh
//get the url
var url = window.location;
//function to get the hostname and pathname
//var l = getLocation(url);
//split the pathname by /
var array = url.pathname.split('/');
//fix the url protocol and hostname for concate
var pathnames = window.location.protocol + "//" + window.location.host;
//loop to get the splited url pathname and insert the each url in specific div
for (i = 1; i < array.length; i++) {
//concatenate the path for each loop
pathnames = pathnames + '/' + array[i];
//appending an ancher tag with href for path in the element with id table_panel_header
$("div#table_panel_header").append(
'<a href="' + pathnames + '">'
+ array[i] + '</a>/');
}
//example text seen as: Complaint_Module/master/complaint-items/
/* example href will append like
<div id="table_panel_header">
<a href="http://localhost:8010/Complaint_Module">Complaint_Module</a>/
<a href="http://localhost:8010/Complaint_Module/master">master</a>/
<a href="http://localhost:8010/Complaint_Module/master/complaint-items">complaint-items</a>/
</div> */