How to remove all URL hashes except first? - javascript

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.

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);

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.

You can use something like -
location.hash = '#'+location.hash.split('#')[1]

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

How to detect parameters globally and keep the state after navigation

I need to find the way to keep the parameters in the url upon navigation if they are entered once, ie: ?aff=john
So for example, user comes to website.com/?aff=john and navigates to about-us I need to make that url parameters are kept, so the full website name is: website.com/about-us/?aff=john
This is what I've tried so far, but it is not working.. it keeps adding the url parameters (window.location.search)
var params = false
var baseUrl = ''
var currUrl = window.location.href
if (window.location.search != '') {
params = true
}
if (params) {
baseUrl = currUrl + window.location.search
window.location.href = baseUrl
}
Thanks.
EDIT: already tried proposed.. not working.
You can use sessionStorage to save navigation data into a key. Pick it up whenever required. Now-a-days, all browsers support it except Opera mini.
Hopefully, your software does not have browser constraints and your application does not have to work on outdated browsers.
As copied from mozilla site, code to use sessionstorage would be like :
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove a key from sessionStorage
sessionStorage.removeItem('key');
// Remove all data from sessionStorage
sessionStorage.clear();
This way, you won't need to append it on every page. For the domain url and in current browser session, you can get it from sessionStorage.
You can save the query string using window.location.search and then you can add link handler in using jQuery like below:
var glString = window.location.search;
$('a').on('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
or if you prefer javascript
var glString = window.location.search;
var links = document.getElementByTagName('a');
links.addEventListener('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
You can temporary save the previous url using sessionStorage.
sessionStorage.setItem('parameter', 'dataString');
sessionStorage.getItem("parameter");

Stripping URL Argument

An example URL that opens my page:
https://mydomain.com/stuff/mypage.php?id=aslkj34rf340if0i3m4flakmf
Is there anyway with javascript to strip everything after .php so that when the user bookmarks the page the bookmark just has https://mydomain.com/stuff/mypage.php as the link?
you need to take a look at this one click me
just use the window.location.search
You can do that by:
var url = document.URL;
var urlparts= url.split('?');
//here is the link you want
var bookmark = urlparts[0];

Clear the # without reloading the page

I am loading all website's pages into the main index page, and updating URL display by splitting the href into segments and adding the segments after the main domain name with .hash function, like this:
$('a').click(function(event) {
event.preventDefault();
var my_url = this.href;
var pathArray = this.href.split('/');
var newPathname = "";
for ( i = 3; i < pathArray.length; i++ ) {
newPathname += "/";
newPathname += pathArray[i];
}
$('body').load(my_url);
window.location.hash = newPathname;
This works okay, but I'm facing a little problem. When a user accesses http://www.mywebsite.com/ and then clicks, for example, on "About" link, the selected page loads, and the address bar displays:
http://www.mywebsite.com/#/about
But if a user starts with a different page:
http://www.mywebsite.com/#/about
Then after the click, the url becomes:
http://www.mywebsite.com/#/about/#/about
and so on, to infinity.
How can this be solved?
Perhaps there's a way to clear the hash and then display the new hash (that is, remove everything that starts with #/ and then add the new hash) – or maybe there's a better solution?
Try var my_url = this.href.replace(/#.*/,'')
This will remove the # and anything after it.
If you want to split just the path component of the current URL, then don’t use
var pathArray = this.href.split('/');
because href will contain the full path including the hash.
Use
var pathArray = this.pathname.split('/');
instead.
Changing the hash doesn't refresh your page. At most it forces the browser to scroll top. If you want you can do:
window.location.hash = "";
to empty it (retaining the #) if you also remove the #from the href then your page will always reload.

Removing # and its value from url

I have seen posts on here to remove the hash value from a url... but how do remove the value and the # itself.
for example if a url was
mysite.com
and when a user navigates through the one page application the url might change to
mysite.com#mytest
so when they reload it i just want it to show
mysite.com and not mysite.com#mytest
these two just remove the value
location.hash = 'home';
window.location.replace("#");
thanks
var href = window.location.href;
var index = href.indexOf('#');
if ( index > 0) {
window.location = href.substring(0, index);
}
I don't think it's possible to remove the hash without reloading the page.

Categories

Resources