javascript - 使用 javascript 检查 url 中的数字?

标签 javascript url hash

我在网站中有一个画廊,每个画廊图像都由一个 url 表示,如下所示:

http://www.example.com/gallery/my-photos#10

http://www.example.com/gallery/my-photos#11

http://www.example.com/gallery/my-photos#12

. . . . .

我已经创建了一个条件语句来防止用户输入无效的 url。

var galleryNum = window.location.hash.substring(1);

if( typeof(galleryNum) == "string" || typeof(galleryNum) == "NaN" ){
    console.log('this is not a number');
}else if(typeof(galleryNum) == "number"){
    console.log('this is a number');
}

但是这不起作用,无论我输入数字还是字符串,我从 window.location.hash.substring(1) 获得的值将始终是一个字符串。

最佳答案

如果你想得到号码,你应该使用:

parseInt(galleryNum,10)

如果你想检查galleryNum是否为数字,你可以使用:

isNaN(parseInt(galleryNum,10))

关于javascript - 使用 javascript 检查 url 中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364687/

相关文章:

c++ - InternetCrackUrl 没有正确返回 lpszHostName

Python - hash() 和 dict

javascript - 循环更新类而不是 id 字段

javascript - 使用数据 : URI? 时有什么方法可以指定建议的文件名

javascript - Extjs、Chrome 扩展和内容安全策略

ruby - 使用 default_proc 初始化所有哈希

ruby - 迭代特定范围的哈希

javascript - 从对象中删除属性的真正方法(删除、空、未定义)

image - Excel VBA自定义函数从URL故障插入图像

javascript - AJAX SEO 友好和历史导航