jet
jet

Reputation: 3

Remove only the last hash of the URL, which was added with window.location.hash

I have a problem with a modal box, which when opened adds a hash to the current url (which may have other hashes)

01

This code works fine for me but leaves this "#" when the hash is removed

window.location.hash = location.hash.replace(/#About/, '');

example when the modal opens: www.mywebsite.com/#products#About

when the modal is closed: www.mywebsite.com/#products#

what I want to get: www.mywebsite.com/#products


02

Also try this one that works fine but eliminates all previous hashes

history.pushState("", document.title, window.location.pathname);

or

history.pushState("", document.title, window.location.pathname + window.location.search);

the results:

when the modal opens: www.mywebsite.com/#products#About

when the modal close: www.mywebsite.com (I do not want the previous hashes removed)


This is my code:

$(".barMenuFooter a.buttonShowDetail").on('click', function(){  
$(this).toggleClass('active');
if ($(this).hasClass("active")) {
    window.location.hash = location.hash + "#About";
    openAbout();    
}
 else {
    window.location.hash = location.hash.replace(/#About/, '');
    closeAbout();   
   } 
 });

I just want to completely remove the last hash added (without the #) without reloading the page.

Upvotes: 0

Views: 283

Answers (1)

Ashar Dweedar
Ashar Dweedar

Reputation: 643

You can use a regexp to find the last "hash" in your url:

 > "site.com/#place1/#place2".replace(/\#$|\#[A-z0-9]*$/, "")
 'site.com/#place1/'

 > "site.com/#place1#".replace(/\#$|\#[A-z0-9]*$/, "")
 'site.com/#place1'

 > "site.com/#place1/#".replace(/\#$|\#[A-z0-9]*$/, "")
 'site.com/#place1/'

/\#$/ This will match the last hash(#) that appears in the end of the string (url).

/\#[A-z0-9]*$/ This will match the last hash(#) that appears in the end of the string(url) with any characters or numbers after it.

Upvotes: 1

Related Questions