Last updated: Oct 26, 2021
Photo from Unsplash
To get the value after the hash:
lastIndexOf()method to get the index of the last hash in the string.
slice()method to get the portion of the string after the last hash.
slicemethod will return a new string containing a portion of the original string.
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.
-1if 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.
1to it's index.