I need to fetch the "NEED_THIS' from the below URL as separate strings.
'https://something--something.lightning.force.com/lightning/o/NEED_THIS/NEED_THIS?inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX29iamVjdFBhZ2UiLCJhdHRyaWJ1dGVzIjp7Im9iamVjdEFwaU5hbWUiOiJTdXBwb3J0X1JlcXVlc3RfX2MiLCJhY3Rpb25OYW1lIjoibGlzdCJ9LCJzdGF0ZSI6eyJmaWx0ZXJOYW1lIjoiUmVjZW50In19&count=1'
Is there any easy way to fetch this?
I already used decodeURIComponent(window.location.href.split('?')[0]); to get upto
https://something--something.lightning.force.com/lightning/o/NEED_THIS/NEED_THIS
First things first,
window.location.protocol = “https:”
window.location.host = “something--something.lightning.force.com”
window.location.pathname = “/lightning/o/NEED_THIS/NEED_THIS”
window.location.search = “?inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX29iamVjdFBhZ2UiLCJhdHRyaWJ1dGVzIjp7Im9iamVjdEFwaU5hbWUiOiJTdXBwb3J0X1JlcXVlc3RfX2MiLCJhY3Rpb25OYW1lIjoibGlzdCJ9LCJzdGF0ZSI6eyJmaWx0ZXJOYW1lIjoiUmVjZW50In19&count=1”
to break the pathname up, you can split it using:
var pathArray = window.location.pathname.split('/');
Then access the different parts by the parts of the array, like
var secondLevelLocationPartOne = pathArray[2];
var secondLevelLocationPartTwo = pathArray[3];
Then you can use it whereever you need it. for reference, click this link
Related
I am just starting to learn location API(s), such as redirection URL in javascript and I can not understand the following three lines,
Can someone explain me?
let windowUrl = new URLSearchParams(window.location.search);
const queryString = window.location.href;
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
The first line is useless. As you can see, windowUrl never gets used.
The following two lines:
window.location.href is nothing but the URL that you see in your browser's location bar. Say, https://www.youtube.com/watch?v=123456
so queryString = "https://www.youtube.com/watch?v=123456"
what the 2nd line does is to take everything that comes after "?" in that string. So v=123456
Then, it splits v=123456 by "=" as a separator. So, finally you get 123456.
Now, all of the above is quite barbaric, as you could obtain the value that "v" parameter this way:
let url = new URL(window.location.href);
let v = url.searchParams.get("v");
URL is an interface that will, shall we say "analyze" a URL and give you methods to parse it conveniently, such as the searchParams method, and more.
MDN https://developer.mozilla.org/en-US/docs/Web/API/URL
Description inline the code:
// for Example: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
windowUrl = new URLSearchParams(window.location.search);
// URLSearchParams object that helps you to provide data to the query url
// window.location.search will return the current search query from your url
queryString = window.location.href;
// the current url: in this case: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]
// you filter or prase the value from the query string
But you can have it easier, like #resle already wrote.
// get the current url
const uri = new URL(window.location.href);
const quersValue = uri.searchParams.get("search");
// output : hello
let windowUrl = new URLSearchParams(window.location.search) ==> fetching URL params from the url. E.g website.com/?hello=1
const queryString = window.location.href; ===> getting the URL of your current page.
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]; ===> String manipulation to get the first param from the URL. Would open dev tool and play with it, to get the feeling.
E.g:
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
console.log(x)
Result: 'hello'
So here's a breakdown of what the code does:
let windowUrl = new URLSearchParams(window.location.search);
Here an instance of a URLSearchParams object which parses the search (effectively the query string).
const queryString = window.location.href;
This grabs the href (i.e. the entire URL including the query string and hash) and names it queryString (very bad name)
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
This grabs the variable named "queryString" which is the href and finds the last index of ? which the code author hoped would designate the place where the query string starts (which is not correct). It then does some string manipulation to attempt get the first query string parameter key which would probably work for most cases but not all.
This code can be greatly simplified to:
const firstParam = (new URL(window.location.href)).searchParams.keys()?.[0];
This will use the JS URL class to parse the URL correctly and get the first key of the search parameters. ?.[0] is the optional chaining operator for arrays
Note that the 3rd line is wrong in this case because a URL like https://example.com/test?param=a&other=b¶m=c#hashwith?questionmark
is valid but the code will think the first URL parameter is questionmark instead of param which would be the expected answer.
I want to extract the domain with a hash without the long random id from the location address bar to make it to show like this:
http://test.example.com/#inbox
Here is the full URL:
http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=
Here is what I have tried so far:
var url = location.hash.split('#inbox')[1];
And I have also tried this:
var url = $(location).attr("href").split('/')[2];
Unfortunately, I didn't get what I want to extract the domain and the hash without the long random id.
When I try it, it extracts the domain name and the hash without the random id to get the return output for the URL like http://test.example.com/#inbox.
I would use indexOf() to find the position of the '#' character. Since the URL can't include a '#', it is safe to assume that the first '#' will be the one you're interested in.
Then I would search for the '/', again with indexOf(), so the word between the '#' and the '/' can change and things still work as expected.
That position is the location of the '/' and anything before that can be returned which is what the String.sub() function does and it returns that URL you're looking for:
var pos = location.href.indexOf('#')
pos = location.href.indexOf('/', pos)
var url = location.href.substr(0, pos)
Another way, although I'm not sure whether it's fully portable, is to use the location fields like so:
var url = location.origin + location.pathname + "#inbox"
If the "#inbox" part can change, you may be able to tweak the code or search for a slash in location.hash like so:
var pos = location.hash.indexOf('/')
var url = location.origin + location.pathname + location.hash.sub(0, pos)
Either way should be plenty fast anyway (especially since you won't need to loop over such).
I got the whole URL, found where the "#" is, added 6 to its count for "#" + the word "inbox", and dropped the rest of the URL:
var url = document.URL;
var i = url.indexOf('#') + 6; // 6 is length of "#" + the word "inbox"
var answer = url.substr(0, i);
Try the code below:
// Complete URL
var url = 'http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=';
var desiredResult = url.match(/.*\/\#inbox\//)[0];
console.log(desiredResult.substring(0, desiredResult.length - 1)); // this will output 'http://test.example.com/#inbox'
I have a URL which will be something like below
http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
I want URL which will be something like this
NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
Here is what I get in variable
VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;
how to get that using javascript. Tried with lastIndexOf but it is not working
You can create a new URL object and use the pathname property to extract the data.
const myUrl = new URL(document.getElementById('ImgPanaromic120').src);
console.log(myUrl.pathname);
<img id="ImgPanaromic120" src="http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg"/>
var a = document.createElement('a');
a.href = 'http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg';
console.log(a.pathname);
window.location.pathname will give you path.
You can simply use window.location.pathname since this is a url.
For other strings, you can use indexOf, split, substring and many of the other string functions.
//example using `split`
var str = "http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg";
var paths = str.split("http://localhost:22306/")
console.log(paths[1]);
I want to get the part of a URL after the last / and before the querystring.
So far I had the last part of the URL, but I wasn't able to remove the querystring from the URL.
The Javascript:
<script type='text/javascript'>
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length-1];
document.write(lastsegment);
</script>
The structure of the URL is like this:
http://www.example.com/search/People?&results=latest
I only need the People part. How could that be possible within the above Javascript?
Or is there any better way to do that?
Try using window.location.pathname instead of window.location.href. It gets only the text between the server name and the query string (which is "/search/People" in your case):
var last_part = window.location.pathname.split('/').pop();
You can read more about pathname here.
Read Window.location
window.location.pathname.split('/').pop();
.pop()
your code does the right thing, you could remove query strings by amending it a bit as;
var lastsegment = array[array.length-1];
if(lastsegment.indexOf('?'))
lastsegment = lastsegment.split('?')[0];
UPDATE:
To handle the case if there are no query string embedded at all.
If you want to parse an URL from another origin than window.location :
var test = 'http://www.example.com/search/People?&results=latest';
var parts = test.split('/');
lastPart = parts[parts.length-1].split('?')[0];
lastPart is now "People"
I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));