How to get the Value after the Hash in JavaScript


Borislav Hadzhiev

Last updated: Oct 26, 2021


Photo from Unsplash

Get the Value after the Hash in JavaScript #

To get the value after the hash:

  1. Use the lastIndexOf() method to get the index of the last hash in the string.
  2. Call the slice() method to get the portion of the string after the last hash.
  3. The slice method will return a new string containing a portion of the original string.
const str = ''; const lastIndexOfHash = str.lastIndexOf('#'); console.log(lastIndexOfHash); // 👉️ 19 const afterHash = str.slice(lastIndexOfHash + 1); console.log(afterHash); // 👉️ 'one-two'

We used the String.lastIndexOf method to get the index of the last hash in the string.

The lastIndexOf method returns -1 if the substring is not contained in the string.

We used the lastIndexOf method because the string might contain multiple hash characters and we want the part after the last one.

The next step is to use the String.slice method to get the string after the hash.

The only parameter we passed to the slice method is the start index - the index of the first character that should be included in the new string.

Because we don't want to include the hash character in the new string, we added 1 to it's index.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.