Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the #id from current URL

I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript. For example:

http://my-page.com/index.html#contact-us

Would return contact-us.

I could split the URI at the eventual # and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.

like image 474
Zar Avatar asked Jul 04 '12 19:07

Zar


People also ask

Is it OK to take ibuprofen after Covid vaccine?

Apply a clean, cool, wet washcloth to your arm to help reduce pain. It may also help to exercise your arm. If you have a fever, drink plenty of fluids and dress lightly. Over-the-counter medicines like Tylenol® (acetaminophen) or Motrin® or Advil® (ibuprofen) can help with pain, fever, headache, or discomfort.

How long does immunity last after Covid?

(2021). Naturally acquired SARS-CoV-2 immunity persists for up to 11 months following infection. The Journal of Infectious Diseases.

Who should not take the Covid vaccine?

Authorized COVID-19 vaccines are safe for most people, with few exceptions: Current vaccines are not authorized for children younger than age 6 months. Individuals who have had severe allergic reactions to other vaccines or injectable therapies should not get vaccinated against COVID-19.

What happens if you take Tylenol before Covid vaccine?

You should not take over-the-counter pain relievers such as aspirin, ibuprofen, or acetaminophen to help prevent side effects before you get the vaccine. It is not known if these medicines will affect how well the vaccine works.


3 Answers

Use location.hash:

location.hash.slice(1);

It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:

$('a').attr('href', url)[0].hash;
like image 176
Rob W Avatar answered Oct 22 '22 15:10

Rob W


location.hash.replace(/^#/, "")

like image 34
pozs Avatar answered Oct 22 '22 14:10

pozs


If you work with a variable:

var url = "http://my-page.com/index.html#contact-us";

var hash = url.substring(url.indexOf("#") + 1);
like image 1
VisioN Avatar answered Oct 22 '22 15:10

VisioN