Matt W
Matt W

Reputation: 4133

JS - What is the difference here?

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions...

First condition (not actually working):

if ( window.location.pathname == '/#register' ) {

// Code

}

Second condition:

if (document.URL.indexOf("#register") >= 0) {

// Code...

}

FYI, this would help me solve a bug I'm experiencing here

Upvotes: 1

Views: 95

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382092

The first checks for an exact match. And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want.

The second one checks the string contains "#register", so the full path could be bigger, like /#register_or_not or /some/other/path#register

Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever:

if (document.URL.match(/.*#register$/)) {

Upvotes: 6

sachin
sachin

Reputation: 14355

This if block check the strings whether they are equal or not

if ( window.location.pathname == '/#register' ) {

 // Code

}

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

if (document.URL.indexOf("#register") >= 0) {

   // Code...

}

Upvotes: 1

Sam
Sam

Reputation: 2970

The second just check if the url contains #register, the first the url path, you can do it also with location.hash

if(location.hash=='#register') { //....

Upvotes: 2

Barmar
Barmar

Reputation: 780688

The first one performs an exact match between window.location.pathname and /#register. The second one looks for #register anywhere in document.URL.

Upvotes: 1

Related Questions