检查字符串是否分裂,防止出现错误
string split and check if parts to prevent errors
假设我们正在研究一个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
, nivel
和seccion
。如果哈希值不存在,这些变量将是一个空字符串。
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
查看该变量中存储了多少个字符串。
相关文章:
- 将字符串拆分为数组时出现JavaScript错误
- gulp Iconify任务抛出错误TypeError:Path必须是字符串.收到false
- 内联javascript与"<脚本>"字符串错误地关闭了脚本标记
- 如何在不创建格式错误的HTML标记的情况下分解字符串
- 如何使用promise正确处理express.js中的错误(字符串或对象)
- 未捕获的类型错误:字符串不是函数
- 错误=字符串.$variable - 失败
- 未捕获的引用错误: 字符串未定义客户端模板.js?rev=J%2BGzwlHEWSv11%2BqD9XeOaw%3D%3
- 未捕获的类型错误:字符串不是函数
- 可以通过主干集合查看错误字符串不是函数
- 使用正则表达式替换XML属性内错误字符串中的嵌套引号
- 抛出新的错误(字符串)不显示在F12
- Json数组中返回错误字符串
- Jquery:使用字符串作为函数(错误:字符串不是函数)
- 如何从没有第一个元素的json对象返回错误字符串
- 从jQuery Ajax调用中获取错误字符串
- 未捕获的类型错误:字符串不是函数,并且没有同名的函数
- 错误:字符串文字未终止
- Chrome在JS控制台上给了我一个错误:“未捕获的无效字符错误:字符串包含无效字符
- javascript语法错误:字符串文字未终止