The JavaScript location hash method is used to get or set the fragment identifier (hash) of the current URL. It takes an optional argument: the new fragment identifier to be set. It returns a string value representing the current or new fragment identifier of the URL.
Here are some examples of how the hash method can be used in JavaScript code:
- To get the current fragment identifier of the URL, you can use the following code:
// get the current fragment identifier of the URL
const hash = location.hash;
- To set a new fragment identifier for the URL, you can use the following code:
// set a new fragment identifier for the URL
location.hash = '#new-fragment';
- To get the current fragment identifier and set a new fragment identifier for the URL, you can use the following code:
// get the current fragment identifier of the URL
const hash = location.hash;
// set a new fragment identifier for the URL
location.hash = '#new-fragment';
Overall, the hash method provides a convenient way to get or set the fragment identifier of the current URL. It can be useful for tasks such as implementing deep linking or anchor links, or for other operations that require accessing or modifying the fragment identifier of the URL.
Leave a Reply