How to get the Value after the Hash in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20211 min read

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.
index.js
const str = 'https://example.com#one-two'; 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee