检查字符串是否分裂,防止出现错误

string split and check if parts to prevent errors

本文关键字:错误 字符串 是否 分裂 检查      更新时间:2023-09-26

假设我们正在研究一个url字符串:

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

,其中我已编纂:

http:/domain.com/en/#{html file}/{id of the div}-{level}
这样我就可以通过 知道
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/

firebug跳出这个错误:

temp1 is undefined

你知道怎么预防吗?

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

下面的代码将始终定义变量url, nivelseccion。如果哈希值不存在,这些变量将是一个空字符串。

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

默认情况下,split方法在Internet Explorer中不起作用,您必须找到一个解决方案,这就是为什么RegEx方法会更好。但是,如果您仍然希望使用split,则可以使用temp.length查看该变量中存储了多少个字符串。