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.
Related
I have stumbled across this issue and hope I can get some inputs here on what could be the cause.
I have a URL with some GET parameters as follows:
www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test
I then extract the parameter to make a REST call
const params = new URLSearchParams(window.location.search);
console.log(window.location.search);
console.log(params.get("serial"));
console.log(params.get("session"));
console.log(params.get("userId"));
const url = new URL("service/resources/query?", document.baseURI).href;
fetch(url + params.toString())
I'd say half of the time my REST call would fail due to session and userId parameters being cut off. Instead, I'm seeing this in my browser
www.test.com/test.jsp?serial=Id123:true
And my console print out would show
?serialNum=ZD0222:True
Id123:True
null
null
Any suggestions on why this happens and how I can write differently here?
Additional note - could the semicolon be the cause here? I noticed that url only show first value of the first parameter.
I think your window.location.search is not what you expect.
Looks good when I explicitly define the URL.
const url = new URL("http://www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test");
const params = new URLSearchParams(url.search);
console.log(url.search);
console.log(params.get("serialNum"));
console.log(params.get("sessionId"));
console.log(params.get("userId"));
I would take another direction, maybe something like
const url = 'http://www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test',
matches = url.match(/([&?](\w*)=([^?&]*))/g),
res = matches.reduce((acc, el)=> {
const sub = el.match(/[&?](.*)=(.*)/)
acc[sub[1]] = sub[2]
return acc
}, {})
console.log(res)
Please note: that function is not dealing with many edge cases, but maybe can inspire You to find an acceptable way to get what You need.
You cannot have colon ( : ) in your URL, its considered as an invalid character. You can use colon only in special cases like specifying port number or in 'http://', etc.
I am having a little problem. I want to get the file name
(横 浜 プ レ _ 図 面 デ ー タ .pdf)
from the url below. I don't know how to use regex to find the file name.
Hope everybody help please.
https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host
Create an URL and let it parse:
const url = new URL(yourUrlString);
Filter the file name:
const fileName = url.pathname.replace(/^.*[\\\/]/, "");
If the filename always follows /attachment/ in the URL, and presumably is always followed with the ? and the rest of the parameters:
Assuming the entire url is assigned to urlString
let startIndex = urlString.indexOf("/attachment/");
let endIndex = urlString.indexOf("?");
let fileName = urlString.substring(startIndex, fileName);
This will find any filename regardless of file type (you mention pdf, but this would find files with other extensions).
var url = 'https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host';
var url2 = url.substring(0, url.indexOf('?X'));
console.log(url2.substring(url2.lastIndexOf('/') + 1));
I guess you can do this without regex
x = "https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host"
y = x.split('/')
["https:", "", "reclaim-files-dev.s3.ap-northeast-1.amazonaws.com", "attachment", "横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&…979a5666e13b54d67f116703&X-Amz-SignedHeaders=host"]
your attachment will be in the 4th index
str = y[4].substr(0, y[4].indexOf('.pdf'))
If you are looking to get the file name from specifically this arrangement of a URL, then simply split by the first argument (?) and then split by forward slash. This will give you an array which you can reverse. The first element of this array will be your file name:
function get_file(url_string){
return url_string.split('?')[0].split('/').reverse()[0];
}
If you want to go a step further, you can then split the result by (.) in order to get the actual name and the file extension in a single step:
function get_file(url_string){
return url_string.split('?')[0].split('/').reverse()[0].split('.');
}
Note: as previously mentioned, this only works with your URL arrangement.
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 have this RegExp: var myReg = RegExp("https?://www.youtube.com/watch\?v=[^\"]+",""); to find the youtube link within a string. I then want to make the part of the string matching the RegExp a variable; lets say var url = "part of string matching the RegExp"
then I coudl do something like window.location = url; to redirect the browser directly to the video page. Thanks
You only have to access the first element of the result, if any:
var r = string.match(myReg);
if(r) var url = r[0];
Take care because is you dont find the url, the result will be a null value
This should do the trick:
myReg.exec(str);
var url = RegExp.lastMatch;
Udi
I have an application that shows photos and albums to a user. Based on current state of the application I show appropriate view. Everytime view changes I change the url, controller then gets the url value using window.location.hash
It returns the string of this form:
"photos/byalbum/albumid"
"photos/allphotos"
"photos/eachphoto/albumid/photoid"
My question is how do I parse this using javscript regular expressions to determine which view I should be showing and also to get the parameters (albumId/photoId)
I think you are better off doing this, then regex:
"photos/eachphoto/albumid/photoid".split("/")
Then you get array that you can examine.
Rather than using regex, you should probably simply split the string on "/" and examine each piece of the value for the data that you need.
var urlString = <your returned value here>;
var urlPieces = urlString.split("/");
var view = urlPieces[1];
var album = (urlPieces[2]) ? urlPieces[2] : "";
var photo = (urlPieces[3]) ? urlPieces[3] : "";
Then play with your data as you wish. :)
If someone is still interesting in this question I used this lib: path-to-regexp to solve that problem.
basically you can convert an url into variables using a pattern.
For example:
const pattern = 'photos/eachphoto/:albumid/:photoid'
const path = 'photos/eachphoto/10/23'
const converter = pathToRegex.match(pattern, { decode: decodeURIComponent })
const params = converter(path)?.params || {}
and params will be similar to: { albumid: "10", photoid: "23" }