Héctor M.
Héctor M.

Reputation: 2392

How to remove all URL hashes except first?

Well, on my site I have a FAQ where users can access specific questions through the URL, such that:

https://example.com/faq#question-1

And for this I use Jquery, such that:

if (window.location.hash) {
    $(window.location.hash).open();
}

But I want that if the user enters more than one hash in the URL such that:

https://example.com/faq#question-1#question-2#question-3#question-n

All hashes are removed from the URL except the first #question-1

How can I do this?

Edit: if user type https://example.com/faq#question-1#question-2#question-3#question-n then change the url to https://example.com/faq#question-1 so that only the first hash appears in the url and the FAQ only has to read a single hash.

Upvotes: 2

Views: 86

Answers (3)

nice_dev
nice_dev

Reputation: 17805

It could something as simple as

var hash = window.location.hash;
var filtered_hash = '';
if(hash.length > 0){
  filtered_hash = '#' + hash.split("#")[1];
  window.location.hash = filtered_hash;
}

console.log(filtered_hash);

Upvotes: 1

Nasir Khan
Nasir Khan

Reputation: 813

You can use something like -

location.hash = '#'+location.hash.split('#')[1]

Upvotes: 1

BlackPearl
BlackPearl

Reputation: 1662

This should work for you

var str="https://example.com/faq#question-1#question-2#question-3#question-n";
var trimmedStr = str.split("#").slice(0,2).join("#");
console.log(trimmedStr);

This removes all hashes after the first hash.

Upvotes: 1

Related Questions