Update last path on the URL with javascript - javascript

I doing a filter system with pagination and i am in a trouble trying to redirect with Javascript depending on the current URL.
I can have this types of URLs where the last number is a filter:
http://localhost/posts/yourPosts/1
http://localhost/posts/subscriptions/3
And inside each type, page 2 will be shown in this way:
http://localhost/posts/yourPosts/1/page:2?url=posts%2FyourPosts
http://localhost/posts/subscriptions/3/page:2?url=posts%2FSubscriptions
I am currently using:
window.location.href = currentURL + '/' + encodeURI($(this).val());
Where $(this).val is the number of the filter to use.
The problem is that when i am in this URLs it works well:
http://localhost/posts/yourPosts/
http://localhost/posts/subscriptions/
But when i am in the 2nd page and i want to show the filter number 3 (lets say, cars instead of animals), it doesn't. It show this:
http://localhost/posts/subscriptions/2/page:2?url=posts%2FyourPosts/3
Instead of this:
http://localhost/posts/subscriptions/3
Is there any simple way to deal with URLs to solve this kind of problem?
I can not either use an absolute path because the URLs are not all the same. So... is there any way to change the last PATH of a URL?

quick and somewhat dirty:
function fixmybadfilterurl(mybadurl)
{
var parts = mybadurl.split('?');
var subpart2 = parts[parts.length-1].split('/');
var subpart1 = parts[0].split('/');
subpart1.pop();
subpart1.pop();
return(subpart1.join('/')+'/'+subpart2[subpart2.length-1]);
}
so
fixmybadfilterurl('http://localhost/posts/subscriptions/2/page:2?url=posts%2FyourPosts/3');
will return
'http://localhost/posts/subscriptions/3'

Related

How to extract specific parameter from different URLs

I've looked on similiar topics but no one seems to answer my question.
I've URL that looks like this:
https://dummy.com/job/test
I need to extract test so I am using:
function getIdentificator(){
let URL = window.location.pathname;
let Id = URL.slice(URL.lastIndexOf('/') + 1);
return Id;
}
It gives me what I want but sometimes the URL is different. For example:
https://dummy.com/job/testwz/something
I only need testwz.
Or:
https://dummy.com/job/test-ab?somethingmore2132
I only need test-ab.
Or:
https://dummy.com/job/test
I only need test.
Or:
https://dummy.com/job/5423
I need 5423 from this.
Value I'm interested in always appear after job/ but in different variations as said before. Key value may be followed by: nothing, / or ?.
Is there any way to extract this value in all examples with JavaScript? If not I can use jQuery as well.
Assuming your path will always begin with /job no matter the domain:
return window.location.pathname.split('/')[2]
I'm going to give you this example:
this is the question's url:
https://stackoverflow.com/questions/54556911/how-to-extract-specific-parameter-from-different-urls
if you do window.location.pathname you will get :
"/questions/54556911/how-to-extract-specific-parameter-from-different-urls"
now, if you do...
window.location.pathname.split('/').pop()
you will get:
how-to-extract-specific-parameter-from-different-urls
And I think this is the answer you are looking for.

Redirection Based on Query String

Not wanting to bloat up an .htaccess with 300 entries, what would be the javascript I could use to redirect to URLs based on a query string in the request to this single file. For example,
https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=57
The only part I care about is the 57 and then redirect it to wherever:
https://www.anothercoolwebsite/secretworld/
In the following case, take the 34 and redirect:
https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=34
https://www.anoldwebsite.com/cool/file.html
Thank you!
This should do you fine. Keep in mind a server-side solution like a PHP script will work for more clients. Since you mentioned .htaccess, I think I should let you know about the fallback resource command
Anyways, here is the JS only solution
function parseString(){//Parse query string
var queryString=location.search.substring(1);//Remove ? mark
var pair = queryString.split('&'); //Key value pairs
var returnVal={};
pair.forEach(function(item,i){
var currPair = item.split('=');//Give name and value
returnVal[currPair[0]]=currPair[1];
});
return returnVal;
}
var links=["index", "about"];//Sample array of links, make sure this matches up with your LinkID
location.href=links[parseString().LinkID]+".html"; //Redirect based on LinkID

JavaScript - find text in URL by position

This should be pretty easy but I'm struggling.
I have a button that fires a function. I want an alert to fire as well that tells me which page the user was on.
www.whatever.com/thispage1/whatever
www.whatever.com/thispage2/whatever
www.whatever.com/thispage3/whatever
So after my button is clicked, I want an alert that reads back "thispage1" or "thispage2" etc. I do not want the entire URL fed back to me. Is there a way to find text in a url based on its position or number of characters before it starts?
Look at window.location.pathname and use str.slice to extract the bit you want, with str.indexOf to find the indices to start/end at
var top_dir = window.location.pathname.slice(
1,
window.location.pathname.indexOf('/', 1)
);
Maybe this will help you get started. Key players here are window.location.pathname and string.split()
var returnPage = function() {
var urlString = window.location.pathname;
var stringArray = urlString.split("/");
return stringArray[0]; // number == whichever piece of the array you want to get
};
function myFunction() {
alert(returnPage());
}

How to count elements of an href?

I have some Javascript that parses out the name of a site so that I can query an XML file to pull data where the node's attribute is the last part of a URL.
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
For example, if the site is http://myexamplesite.com/status-Blah00 I would be able to get all data out of the Blah00 XML node and populate various aspects of the site with whatever is in the XML.
This works fine and I am able to use the URL name (Status-Blah00, Status-Blah01, etc.) to query XML against it and populate elements on the page based on the name of the site.
However I ran into problems where a site has a second - in the URL.
For example:
http://myexamplesite.com/status-Blah01-Blah00.htm
It should be parsing the Blah01-Blah00 node of my XML, but instead of just gets the data from Blah00 since it doesn't recognize the first -. I'm new to javascript and I'm confused as to how to basically do:
if 1 "-" in url then get last index
else the number of "-" in url is > 1, get first index.
How would I be able to count the number of "-" in the URL and logically do just that with the above Javascript?
You could use a regex for this problem. Here is a start:
"status-Blah01-Blah00.htm".match(/([^-]+)/g)
That code generates the array:
["status", "Blah01", "Blah00.htm"]
So you can work with the length of that array to find out how many hyphens are in the url.
Even easier: "status-Blah01-Blah00.htm".split('-') returns the same array.
Here is a single line with sequential regexes that can handle dashes occurring elsewhere in the url and that keeps the Blah01-Blah00 node as a single string rather than separating them, as it seems you requested.
"http://www.site-name.com/folder-name/01-10-20/status-Blah0100-Blah01.htm".match(/-([^.\/]+)\.htm/g)[0].match(/[A-z0-9][A-z0-9\-]+/g)[0]
Generates:
"Blah0100-Blah01"

Appending query strings from multiple pages

I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.

Categories

Resources