Javascript拆分URL

时间:2013-08-15 14:20:47

标签: javascript arrays split

我想拆分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>

网址结构如下:

http://www.mydomain.com/page/2013/05/some-page-title.html

变量query输出如下; page,2013,05,some-page-title

我只想要some-page-title部分并删除连字符。

所以最终输出为http://www.mydomain.com/search/?q=some page title

怎么可能?请帮忙!! 感谢

2 个答案:

答案 0 :(得分:6)

Split返回一个数组,将其用作数组!

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];

这假设你总是想要在最后/

之后的网址部分

答案 1 :(得分:1)

//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> */