使用javascript从位置拆分网址

时间:2013-10-18 10:43:23

标签: javascript parsing url split

我需要解析网址:

http://localhost.com/kw-webapp/preview/cn/1/cmm/Default/13203/content.13203.1.1.html?context=

var url = window.location.pathname.split( '/' );

                var _language = 4;
                var _layoutuid = 5;
                var _themeuid = 6;
                var _contentuid = 7;
                var _content = 8;

                var language = url[_language];
                var layoutuid = url[_layoutuid];
                var themeuid = url[_themeuid];
                var contentuid = url[_contentuid];
                var content = url[_content];

但我需要从这个位置解析网址:

CN / 1 / CMM /默认/ 13203 / content.13203.1.1.html?上下文=

和变量必须是:

var _language = 0;  //1
                var _layoutuid = 1; //cmm
                var _themeuid = 2;  //Default
                var _contentuid = 3;    //13203
                var _content = 4;

我的问题是,网址可以这样开始:

www.localhost.com/kw-webapp/kw/preview/cn/1/cmm/Default/13203/content.13203.1.1.html?context =

左右:

www.localhost.com/preview/cn/1/cmm/Default/13203/content.13203.1.1.html?context =

我如何解析网址 CN / 1 / CMM /默认/ 13203 / content.13203.1.1.html?上下文=?

提前致谢!

P.S。对不起我的englisch

1 个答案:

答案 0 :(得分:1)

如果您的网址始终为*preview/cn/*,并且您想要其最后一部分,则可以使用RegExp修剪网址,如下所示:

var trimmedURL = "http://localhost.com/kw-webapp/preview/cn/1/cmm/Default/13203/content.13203.1.1.html?context=".replace(/.*preview\/cn\//,'');
//console.log(trimmedURL);
var url = trimmedURL.split( '/' );

Demo Fiddle