2011-12-28 24 views
1

让说我们是天花板高度URL字符串:由字符串分割,并检查零件,以防止错误

http:/domain.com/en/#{html file}/{id of the div}-{level} 

这样我可以知道:

http:/domain.com/en/#the-file.html/section-4 

在那里我有成文

var info = window.location.hash; 
var temp = info.split("/"); 
var url = temp[0]; 
url = str_replace('#','',url); 
var temp1 = temp[1]; 
temp1 = temp1.split('-'); 
var seccion = temp1[0]; 
var nivel = temp1[1]; 

其中

console.log('url: '+url); 
console.log('info: '+nivel); 
console.log('seccion: '+seccion); 

我提供这些编纂瓦尔

问题时,例如,URL是

http://domain.com/es/ 

是萤火虫跳这个错误:

temp1 is undefined 

任何想法如何预防?

回答

2

而不是使用split,我建议使用RegExp,当多个斜杠或连字符出现时不会中断。

以下代码将始终定义变量url,nivelseccion。如果散列不存在,这些变量将是一个空字符串。

var info = window.location.hash.match(/^#(.*?)\/(.*?)-(.*)$/), 
    url="", nivel="", seccion=""; 
if (info) { 
    url = info[1]; 
    nivel = info[2]; 
    seccion = info[3]; 
} 
+0

嘿!谢谢!工作和看起来更好:) – 2011-12-28 13:01:27

1

split方法并不默认在Internet Explorer中工作,你必须找到a workaround,这就是为什么一个正则表达式的方法会更好。但是,如果您仍想使用拆分,则可以使用temp.length来查看该变量中存储了多少个字符串。

+0

错误不是由IE中的不兼容性问题引起的,错误是由数组大小为0或1,如果没有找到匹配的事实引起的。因此,'temp [1]'是未定义的。因此,'temp [1] .split'会抛出一个ReferenceError。 – 2011-12-28 13:11:02

+0

@Rob我知道,这就是为什么我推荐temp.length,但是如果他使用split,他应该记住,这将在IE中破解。 – 2011-12-28 13:14:05