2

How can we get only hash value without query params using javascript/jquery ?

Problem is,

http://www.somedomain.com/me/terms.html#terms - location.hash.substr(1) - terms

http://www.somedomain.com/me/terms.html#terms?queryParam=1 - location.hash.substr(1) - terms?queryParam=1

we can parse the URL and get the hash value but is there any direct/efficient methods available javascript/jquery ?

1

4 Answers 4

2

The fragment identifier should be AFTER the query string. From Wikipedia:

The syntax (for url scheme) is: scheme://domain:port/path?query_string#fragment_id

This is important, as in your example the query string would not reach the server. If you are using a front-end library, you might have access to some APIs that let you access it though. The $location service in AngularJS by default addresses ONLY the part after the first hash (as the hash indicates routing start for the front-end app). https://docs.angularjs.org/guide/$location

in your case, $location.path() would equal terms and $location.search() would equal queryparam=1; $location.hash() would be null.

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct way to use the hash. Now im changing backend. Thanks Wiherek.
0

Easiest way would probably be to use a regex that starts on the hash and ends on the ? or end of string. Something like this:

/#(.+)\??/gi

First capture group should yield out the contents of the hash.

1 Comment

Still I'm getting confused - terms.html#terms?param-1 - location.href.match(/#(.+)\??/gi) - ["#terms?param=1"]
0

Don't even have to regex. It is already here as part of Javascript with location.hash;

Assume that the current URL is http://www.example.com/test.htm#part2: var x = location.hash; The result of x will be: #part2 

http://www.w3schools.com/jsref/prop_loc_hash.asp

2 Comments

Thanks. But this only works for test.html#part2 not for test.html#part2?queryParamm=1
Ahh understood, then use Paul's method with regex to pull in the items
0
 test.html#part2?queryParamm=1 

window.location.hash give #part2

window.location.search give ?queryParamm=1

for more see http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.