1

I've a gallery within a website and each gallery image is represented by a url like so:

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

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

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

. . . . .

I've created a conditional statement to prevent user from invalid 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');
}

However this doesn't work, the value I get from window.location.hash.substring(1) will always be a string regardless I enter number or a string.

3 Answers 3

3

if you want to get number, you should use:

parseInt(galleryNum,10)

if you want to check whether galleryNum is number or not, you can use:

isNaN(parseInt(galleryNum,10))
Sign up to request clarification or add additional context in comments.

2 Comments

you should add the radix parameter: parseInt(galleryNum, 10)
Yes you definitley should use the radix parameter it does some unwanted things in older versions of ecmascript.
3

Try utilizing .test()

if( /\d/.test(galleryNum) ) {
  // `Number`
} else {
  // not `Number`
}

Comments

2

there is no "NaN" type. In fact, despite NaN standing for Not-a-Number, it actually is a number: typeof NaN === 'number'

You can however use isNaN() to test for NaN. To test if the string returned from the URL can be cast to a number, use parseInt:

var galleryNum = parseInt(window.location.hash.substring(1),10);
if (typeof(galleryNum) === 'number' && !isNan(galleryNum)) {
    // got a number here
}

3 Comments

This is true, but it still doesn't solve his problem.
You are right. I was focusing on an irrelevant part of his question.
That's okay it's good for him to know either way. It may be better suited as a comment though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.