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" }
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 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.
What I'm about to ask may sound stupid but I've been trying to figure it out for a few days now. I want to generate a link to a site:
example.github.io/Example/Example
That has a variable or something at the end of it
example.github.io/Example/ExampleVariable
and then read that variable as the page loads. In a perfect world it would look something like this:
http://Example.github.io/Example/Example<script>function(){}</script>
I also need to make sure that the page the user actually goes to or at least ends up on is the original link: i.e.
example.github.io/Example/Example
Any help would be greatly appreciated.
Also if anyone is wondering. Yes it is on github if that applies. I barely know PHP so that's not the best. It's for a ToDo list manager app I've made. There is a load function so users can share lists. The Load string (variable I'm trying to read) looks like this: /LoadNAME#THEME#Item A,Item B,ect.
If you're using github pages you could use URL parameters. In that case the url would look something like this: http://mypage.github.io/test/?myparam=value
Then you could query that with javascript and execute something based on that url parameters the url contains.
Alternatively, you can use this hash # old trick then after it use slashes
example.github.io/Example/#/var1/var2/var3
then using the window.location.href with couple split() uses will provide you
with an array of parameters.
/* URL in address bar:
http://localhost/test/js-url-parameters/#/str1/str2/str3/
*/
var docURL = window.location.href,
params = [];
// filter out the website origin "example.github.io" in the OP example
docURL = docURL.replace(window.location.origin, '');
// if /#/ found then we have URL parameters
// grabbing the parameters part of the URL
if (docURL.indexOf('/#/') > -1) {
docURL = docURL.split('/#/')[1];
if (docURL != '') {
// omit the last forward slash if exist
if (docURL[docURL.length - 1] == '/') {
docURL = docURL.substring(0, docURL.length - 1);
}
// split the URL final string o get an object with all params
params = docURL.split('/');
console.log(params);
}
} else {
console.log('No URL parameters found');
}
/* Output:
["str1", "str2", "str3"]
*/
UPDATE:
The above outputs all variables as string, so to retrieve numeric values you need to parseInt -or parseFloat() depending on your case.
For example, if for this URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/
The above code will output ["str1", "22", "str3"], while we suppose to have 22 as integer, to fix this just add this:
// for each elements in params, if it is Not a Number (NaN) we return
// it as it is, else it's a nubmer so we parseInt it then return it
for(var i in params){
params[i] = isNaN(parseInt(params[i])) ? params[i] : parseInt(params[i]);
}
the above snippets go rights after the params = docURL.split('/'); line.
Now the URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/ outputs ["str1", 22, "str3"], as you see now 22 is a number rather than a string.
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
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