我在网站中有一个画廊,每个画廊图像都由一个 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/