How can i pass params in url like a path in javascript? - javascript

How can I get the params from the URL path as we do in Django?
For example if the url is domain.dom/userid,
then we need userid as a param in js and redirect to domain.dom.
Is this possible in javascript?

Try this
let url = new URL("https://domain.dom/freddy_user"); // new Url(location.href)
const userid = url.pathname.slice(1);
url.pathname="index.html";
url.searchParams.set("userid",userid)
console.log(url); // location.replace(url)

If you need the current URL and params, this could help you
I'am considering that the userID param is the first param like:
url.com/123
where 123 is the userID
//Get current base URL
let base_url = window.location.origin;
//Get userID or first param
//Change number 3 if your param is in another position
let userId = window.location.href.split("/")[3];
alert(userId);
//Redirect to base URL
window.location.href = base_url;

This can be achieved by redirecting through the .htaccess file and further
var path = location.pathname; var arr = path.split("/"); var name = arr[arr.length-1];
Hence, with this, we can achieve the parameters through the domain path in javascript.

Related

Get Base URL from Javascript Helper function in a Laravel Project

I can Get base url of my laravel project from blade file in javascript section by using this
var APP_URL = {!! json_encode(url('/')) !!}
But what should i do to get the base url when i am in a helpers.js like file
isValid(token){
const payload = this.payload(token);
if(payload) {
return payload.iss == "http://127.0.0.1:8000/" || "http://127.0.0.1:8000/register" ? true : false
}
return false
}
i want to get base url here rather asssigning the url separately.
Can anyone Help Me?
Use this to get base url in javascript.
var base_url = window.location.origin;
Check it
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
You Can Use like this:
var baseUrl = window.location.origin;
// "http://google.com"
var host = window.location.host;
// google.com

get the hostname(Base URL) using javascript

I get too many ways to get the hostname like code below:
window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath
In my case I want something different. For example:
My QA site name is example.com/testsite/index.html
My PROD site name is example.com/index.html
The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com
However for QA I need to return example.com/testsite
For PROD i need to return example.com
Is it possible with the single code? Thanks in advance.
To achieve what you require you'll need to check the window.location.hostname, and also the first folder in the window.location.pathname. Something like this:
function getPath() {
var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
return window.location.hostname + folder;
}
Best method that works for both PROD & QA
var BASE_URL = window.location.href;
BASE_URL = BASE_URL.split("testsite");
if (BASE_URL.length > 1)
{
BASE_URL = BASE_URL[0];
BASE_URL = BASE_URL + 'testsite';
} else{
BASE_URL = window.location.origin;
}
Use window.location.hostname;
Example:
Page URL is http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh
var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh
var getHostname=window.location.hostname; //localhost
var getPathName=window.location.pathname // Default2.aspx
var getPortNo=window.location.port // 2239
var getQueryString=window.location.search //?id=5&name=SatinderSingh
var getHostname = window.location.hostname; //localhost
var getPathName = window.location.pathname // Default2.aspx
var split_PathName = String(getPathName.split("/"));
var FinalURL = getHostname + "/" + split_PathName[1]

How get root url path

I'm searching a way to get the root URL of my Web project; as example:
Local:
http://localhost:52390/pages/user.aspx
Expected result: http://localhost:52390
IIS:
http://lst.pg.com/iLearn/pages/user.aspx
Expected result: http://lst.pg.com/iLearn
Exists a way to achieve this in ASPX? Or in Javascript/jQuery?
in javascript you can get url information from the location object.
var href = location.href; //returns the entire url
var host = location.hostname; //returns just the hostname of the url.
ASPX: Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
Implemented with Javascript:
<script type="text/javascript">
var rootUrl = '<% =(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath) %>';
</script>
There are times I need to get the rootpath from the code behind. Here is what I use.
public static string GetRootPath()
{
HttpContext CTX;
CTX = HttpContext.Current;
return CTX.Request.ApplicationPath.ToString();
}

How can I extract and then change the url path using javascript?

I am trying to extract part of the url and replace it with custom text using javascript.
For example, I want to fetch the current url such as:
mydomain.com/url_part_to_change/some-other-stuff
and then change that url to insert so that new new url is:
mydomain.com/new_url_part/some-other-stuff
Here is what I have:
function changeURL() {
var theURL = window.location.pathname;
theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
}
However, when I try to call the function changeURL(), it returns undefined instead of the new url.
For example if I do this:
alert(changeURL());
then what alerts is undefined
TL;DR
// update the pathname that will reload the page
window.location.pathname = myNewPathname;
Further Explanation:
Window.location ( image attached below ) provides you an object containing all the uri parts information. So, you can get this object via window.location and access the property pathname then do your stuffs. For example:
var locationObject = window.location;
var pathnameToChange = locationObject.pathname;
// do stuffs to "copy" of pathname, this will not reload the page
var myNewPathname = doSomethingMyPathname( pathnameToChange );
Additional Examples:
Alternatively, set new url using location.href. Check the MDN documentation for examples on location.assign(), location.replace(), location.reload() and notes on the different available functions
// ie.myNewUrl is something I created -> www.blah.com/updated/path
window.location.href = myNewUrl;
// or
window.location.assign(myNewUrl)
A window.location Object in Console
There are three references to further understand URI components
URI_scheme
Standards written by Tim Berners-Lee
MDN Location
Hope this helps.
This should work for you correctly:
function changeURL() {
// Get the url, just as you did
var theURL = window.location.pathname;
// Return the url
return theURL.replace("/url_part_to_change/", "/new_url_part/");
}
you are not returning any thing in function, Please make function like
function changeURL() {
var theURL = window.location.pathname;
return theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
}
As the others said, you don't return anything. What they are forgetting is that String.replace() just makes a copy of theURL and doesn't change theURL.
Try this:
function changeURL() {
var theURL = window.location.pathname;
theURL = theURL.replace("/url_part_to_change/", "new_url_part/");
//Set URL
return theURL;
}
alert(changeURL());
function changeURL() {
//set new path
window.location.pathname = "/new_url_part/";
//get new url
const newURL = window.location.href;
return newURL;
}
You forgot to return
function changeURL() {
var theURL = window.location.pathname;
var newURL = theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
return newURL;
}
alert(changeURL())//Now you won't see undefined.
This is quite an old post but just to add:
modifying window.location causes page navigations so if thats not desired create a new URL object and then you can modify the parts as needed.
in my case i needed to change the path to a value from a value in the querystring.
eg.
/*
* http://something.com/some/path?redirect=/some/other/path
* ->
* http://something.com/some/other/path
*/
let u = new URL(window.location.href)
u.pathname=u.searchParams.get("redirect")
u.searchParams.delete("redirect")
console.log(u.href)

update parameters in URL with history.pushState()

I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL again with same or additional set of params. So my code looks like this:
var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);
queryString is my list of query params.
For example, My Default page URL: http://sample.com/
After First AJAX call on same page URL should be: http://sample.com?param1=foo&param2=bar
After Second AJAX call on same page URL can be:
http://sample.com/?param1=foo,foo1&param2=bar&param3=another_foo
But with the above code my params are getting appended to URL with the params and they look like below after second AJAX call:
http://sample.com?param1=foo&param2=bar&param1=foo,foo1&param2=bar&param3=another_foo
So the params appear twice in the URL, is there any way of replacing the params in URL before pushing to History or any other better way to achieve this in javascript(jquery) ?
I think what you need is remove window.location.href and leave '?' +.
var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);
This function might be helpful
function updateUrlParameter(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).
function setQueryStringParameter(name, value) {
const params = new URLSearchParams(window.location.search);
params.set(name, value);
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}
In order to keep the last part of the url and just play with parameters, you can create a new URL object like so:
// e.g url: sample.com/testpage/test
var url = new URL(window.location);
url.searchParams.set('foo', 'bar');
window.history.pushState({}, '', url);
// outcome: sample.com/testpage/test?foo=bar
// you can remove, just the param part, like so:
url.searchParams.delete('foo');
Manage query parameters in the current URL
This function is similar to the other answers, but without using RegExp and string concatenations.
Args:
name - string name of the query parameter.
value - string value of the parameter.
append - if true: this function always adds a new parameter. This is very useful when you need to add two parameters with the same name, e.g.: localhost:8080/some_page?foo=100500&foo=ABC. Otherwise, the parameter will be changed (or added if absent).
function setQueryStringParameter(name, value, append=false) {
const url = new URL(window.document.URL);
if (append) url.searchParams.append(name, value);
else url.searchParams.set(name, value);
window.history.replaceState(null, "", url.toString());
}

Categories