2

I am working on how to get #pg value from URL using JavaScript, I tried

var url_string = "http://example.com/aus/#pg=0"; //window.location.href
var url = new URL(url_string);
var pg = url.searchParams.get("pg");
console.log(pg);

But not getting any result, Please help

1
  • ....you should check the definition of search params ;) Commented May 19, 2020 at 6:37

1 Answer 1

0

For this snippet to work, you have to replace() # with ? to make a valid SearchParam:

var url_string = "http://example.com/aus/#pg=0"; //window.location.href
var url = new URL(url_string.replace('#', '?'));
var pg = url.searchParams.get("pg");
console.log(pg);

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

4 Comments

Why not simply read the hash property?
I know window.location.hash this could be the solution, but my snippet because he is asking why it not working, also this can be a string from <a> tag not a URL
If the string would come from a link, the same hash property applies. Randomly replacing stuff in the URL might cause problems, especially if the URL already contained a query string
@NicoHaase, I agree with you. got the point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.