Evanss
Evanss

Reputation: 23593

Remove # character from url with jQuery

With this jQuery I can change the url of my site from mysite.com/#oldurl to mysite.com/newurl:

$('.trigger').click(function() {
    history.pushState('data', '', 'newurl');
});

How can I make it so the # is always striped out and the rest of the url left. So mysite.com/#page2 becomes mysite.com/page2, mysite.com/#page3 becomes mysite.com/page3, etc.

Upvotes: 0

Views: 1544

Answers (5)

Adam Merrifield
Adam Merrifield

Reputation: 10407

I may be misreading the question, My thought when you say # is the current URL minus the hash.

You can create a jQuery a element with window.location to build the current url. Use this variable to parse the current url parts. Also you might want to check if pushState is available before you use it.

if(history.pushState){
    var a = $('<a>', {href: window.location})[0];
    history.pushState(null, null, a.pathname+a.hash.substr(1));
}

Upvotes: 0

Evanss
Evanss

Reputation: 23593

This is my use of "On a serious note"'s code:

$('.trigger').click(function() {

    var oldURL = window.location.hash;
//  console.log('newURL ', oldURL);

    var final_url="";
    final_url=oldURL.replace('#', '');
    history.pushState('data', '', final_url);

//  console.log('final_url', final_url);

});

Upvotes: 0

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

$('.trigger').click(function() {
 var final_url="";
if(your_url.indexOf('#') != -1)
{
  final_url=your_url.replace('#', '');
}

history.pushState('data', '', final_url);
});

Upvotes: 0

codingrose
codingrose

Reputation: 15699

Try:

newurl = oldurl.replace(/#/g,"/");

Upvotes: 0

Somnath Kharat
Somnath Kharat

Reputation: 3610

U can use replace

var newurl=oldurl.replace("#","");

Upvotes: 3

Related Questions