【问题标题】:string split and check if parts to prevent errors字符串拆分并检查是否部分以防止错误
【发布时间】:2011-12-28 12:55:17
【问题描述】:

假设我们正在研究一个 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);

为我提供那些编码的变量

问题在于,例如,网址是

http://domain.com/es/

那个萤火虫会跳这个错误:

temp1 is undefined

知道如何预防吗?

【问题讨论】:

    标签: javascript jquery split


    【解决方案1】:

    我建议不要使用split,而是使用正则表达式,它不会在出现多个斜杠或连字符时中断。

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

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

    【讨论】:

      【解决方案2】:

      split 方法在 Internet Explorer 中默认不起作用,您必须找到 a workaround,这就是 RegEx 方法更好的原因。但是,如果您仍想使用 split,您可以使用 temp.length 查看该变量中存储了多少字符串。

      【讨论】:

      • 该错误不是IE中的不兼容问题引起的,该错误是由于数组大小为0或1,如果没有找到匹配项引起的。因此,temp[1]undefined。因此,temp[1].split 会引发 ReferenceError。
      • @Rob 我知道,这就是我推荐 temp.length 的原因,但如果他使用 split,他应该记住这会在 IE 中中断。
      猜你喜欢
      • 2019-06-21
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2013-03-03
      相关资源
      最近更新 更多