2010-11-25 67 views
0

我有一个JavaScript脚本我需要修改帮助...
我想将URL部分提取并设置为html元素的类。提取URL部分的正则表达式?

var loc = window.location.pathname.match(REGEX_CODE_GOES_HERE); 
// document.documentElement is the html element, this adds the class 
if(loc) document.documentElement.className += " " + loc[1].toLowerCase(); 

困难的部分是正则表达式;这是它如何工作:

实例网址:

http://www.somesite.com/Lists/Pages/ViewPage.aspx?ID=12 

应该返回(如HTML元素的课程,课程的):

lists pages viewpage aspx id 12 

随意反正周围编辑代码你似乎适合...

在此先感谢!

回答

3

var split = window.location.pathname.split(/\/|\?|&|=|\./g);

,或者如果你在一个字符串希望所有:

var classes = window.location.pathname.toLowerCase().replace(/\/|\?|&|=|\./g," ") 

可以做你想做的

+0

我建议使用`\ W`而不是特定的字符,如果JavaScript支持这一点。 – 2010-11-25 10:57:27

+0

但在参数中可能存在非字词字符,您不想将其作为分隔符 – morja 2010-11-25 11:02:41

2
var matches = window.location.pathname.replace(/http:\/\/[^\/]+\//,'').match(/[\w\-\.!~\*\'"(),]+/g); 

正则表达式与RFC 1738规定。

将每个数组元素转换为小写应该是一件小事。

1
var match = url.match(/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/); 
var protocol = match[1], 
    domain = match[2], 
    path  = match[3], 
    query = match[4], 
    fragment = match[5];