How to get url parameters with same name from URL in js? - javascript

For example I have this url
https://www.test.com/test.html?categoryid=4&test1=12&test2=65&brand[0]=val1&brand[1]=val2&test3=15
Now how do I get value of brand[0]=val1&brand[1]=val2 but it can be any number of there in the url maybe brand[2],brand[3] etc... or none url can be without this parameter
I need to get if brand parameter is in url and if yes then I need to get all which are availabe in the url
Any help would be great!

So you don't really know if there would be parameters or not so that's why I can propose this solution right here it will parse all your parameters anyways and stack them in the config JSON in case there is no parameters config would be empty then on your DOMloaded event you can handle the cases as you want
const config = {};
const loadConfig = () => {
const urlQuery = new URLSearchParams(window.location.search);
urlQuery.forEach((e, k) => {
config[k] = e;
});
};
const onLoadEvent = () => {
console.log(config) // should contain all the query string params.
}

Related

How to get avatar file type [duplicate]

How do I find the file extension of a URL using javascript?
example URL:
http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294
I just want the 'swf' of the entire URL.
I need it to find the extension if the url was also in the following format
http://www.adobe.com/products/flashplayer/include/marquee/design.swf
Obviously this URL does not have the parameters behind it.
Anybody know?
Thanks in advance
function get_url_extension( url ) {
return url.split(/[#?]/)[0].split('.').pop().trim();
}
example:
get_url_extension('https://example.com/folder/file.jpg');
get_url_extension('https://example.com/fold.er/fil.e.jpg?param.eter#hash=12.345');
outputs ------> jpg
Something like this maybe?
var fileName = 'http://localhost/assets/images/main.jpg';
var extension = fileName.split('.').pop();
console.log(extension, extension === 'jpg');
The result you see in the console is.
jpg true
if for some reason you have a url like this something.jpg?name=blah or something.jpg#blah then you could do
extension = extension.split(/\#|\?/g)[0];
drop in
var fileExtension = function( url ) {
return url.split('.').pop().split(/\#|\?/)[0];
}
For the extension you could use this function:
function ext(url) {
// Remove everything to the last slash in URL
url = url.substr(1 + url.lastIndexOf("/"));
// Break URL at ? and take first part (file name, extension)
url = url.split('?')[0];
// Sometimes URL doesn't have ? but #, so we should aslo do the same for #
url = url.split('#')[0];
// Now we have only extension
return url;
}
Or shorter:
function ext(url) {
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('#')[0].substr(url.lastIndexOf("."))
}
Examples:
ext("design.swf")
ext("/design.swf")
ext("http://www.adobe.com/products/flashplayer/include/marquee/design.swf")
ext("/marquee/design.swf?width=792&height=294")
ext("design.swf?f=aa.bb")
ext("../?design.swf?width=792&height=294&.XXX")
ext("http://www.example.com/some/page.html#fragment1")
ext("http://www.example.com/some/dynamic.php?foo=bar#fragment1")
Note:
File extension is provided with dot (.) at the beginning. So if result.charat(0) != "." there is no extension.
This is the answer:
var extension = path.match(/\.([^\./\?]+)($|\?)/)[1];
Take a look at regular expressions. Specifically, something like /([^.]+.[^?])\?/.
// Gets file extension from URL, or return false if there's no extension
function getExtension(url) {
// Extension starts after the first dot after the last slash
var extStart = url.indexOf('.',url.lastIndexOf('/')+1);
if (extStart==-1) return false;
var ext = url.substr(extStart+1),
// end of extension must be one of: end-of-string or question-mark or hash-mark
extEnd = ext.search(/$|[?#]/);
return ext.substring (0,extEnd);
}
url.split('?')[0].split('.').pop()
usually #hash is not part of the url but treated separately
This method works fine :
function getUrlExtension(url) {
try {
return url.match(/^https?:\/\/.*[\\\/][^\?#]*\.([a-zA-Z0-9]+)\??#?/)[1]
} catch (ignored) {
return false;
}
}
You can use the (relatively) new URL object to help you parse your url. The property pathname is especially useful because it returns the url path without the hostname and parameters.
let url = new URL('http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294');
// the .pathname method returns the path
url.pathname; // returns "/products/flashplayer/include/marquee/design.swf"
// now get the file name
let filename = url.pathname.split('/').reverse()[0]
// returns "design.swf"
let ext = filename.split('.')[1];
// returns 'swf'
var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
alert(doc.substring(doc.lastIndexOf(".")))
const getUrlFileType = (url: string) => {
const u = new URL(url)
const ext = u.pathname.split(".").pop()
return ext === "/"
? undefined
: ext.toLowerCase()
}
function ext(url){
var ext = url.substr(url.lastIndexOf('/') + 1),
ext = ext.split('?')[0],
ext = ext.split('#')[0],
dot = ext.lastIndexOf('.');
return dot > -1 ? ext.substring(dot + 1) : '';
}
If you can use npm packages, File-type is another option.
They have browser support, so you can do this (taken from their docs):
const FileType = require('file-type/browser');
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const response = await fetch(url);
const fileType = await FileType.fromStream(response.body);
console.log(fileType);
//=> {ext: 'jpg', mime: 'image/jpeg'}
})();
It works for gifs too!
Actually, I like to imporve this answer, it means my answer will support # too:
const extExtractor = (url: string): string =>
url.split('?')[0].split('#')[0].split('.').pop() || '';
This function returns the file extension in any case.
If you wanna use this solution. these packages are using latest import/export method.
in case you wanna use const/require bcz your project is using commonJS you should downgrade to older version.
i used
"got": "11.8.5","file-type": "16.5.4",
const FileType = require('file-type');
const got = require('got');
const url ='https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const stream = got.stream(url);
console.log(await FileType.fromStream(stream));
})();
var fileExtension = function( url ) {
var length=url.split(?,1);
return length
}
document.write("the url is :"+length);

Best way to add query param to all navigations

I am looking for a solution to add query param on each URL after navigation using WebDriverIO.
For example:
Base URL: https://www.google.com/?block=true
When I click a button on the page loaded from the above URL, new URL that loads is https://www.google.com/search-page.
I would like to append ?block=true to all the navigations.
For the base URL, I can use the method browser.url("https://www.google.com/?block=true"). Not sure how I can add to other pages that are navigated using click actions.
You can use URLSearchParams to generate complex search params. Check out the below example.
const baseUrl = "https://www.google.com/?block=true"; // window.location.href
const searchUrl = "https://www.google.com/search?test=testparam";
function getRedirectUrl(baseUrl, newUrl) {
let oldParms = new URL(baseUrl).searchParams;
const newUrlParams = new URL(newUrl).searchParams;
for(let [value, key] of oldParms.entries()){
newUrlParams.append(key, value);
}
const newSearch = new URL(newUrl).search;
return `${newUrl.slice(0, -1 * newSearch.length)}?${newUrlParams.toString()}`;
}
console.log(getRedirectUrl(baseUrl, searchUrl));

how do i extract id parameter from an URL using reactjs

http://localhost:3000/messages/?qr_asset_id=1f6b997464&gts=1627828213
this is an URL, I need to extract the qr_asset_id value from this URL
how do I do this with reactjs
As you're using hooks based on your used tags:
const location = useLocation();
const urlParams = new URLSearchParams(location.search);
const paramValue = urlParams.get('qr_asset_id');
You pull it from the props. props.match.params.qr_asset_id
You can use URLSearchParams.
check for browser compatibility first
const url = window.location.href // "http://localhost:3000/messages/?qr_asset_id=1f6b997464&gts=1627828213";
const searchParams = new URLSearchParams(url);
const qrAssetId = searchParams.get("qr_asset_id"); // 1f6b997464
query parameter guide in react-router should help.
There are url-polyfill libraries out there too. You can use them to get the same result.
url-polyfill
whatwg-url

Issues with identifying and encoding urls

I'm having issues with parsing/manipulating URI:
Problem Statement:
I want to encode f[users.comma] and return it.
[Case-1] I get an url from backend service, encode f[users.comma] and return it.
[Case-2] I get an url from backend service and f[users.comma] is already encoded. So don't double encode and return it.
Expected Output:
`/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22`
Code:
const encodedExample = `/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22` // the last param is encoded
const regularExample2 = `/demo/bigquery/order_items?fields=users.email&f[users.comma]="Abbeville, Georgia"` //
const specialEncode = (url) => {
for (let queryParam of urlObj) {
const [urlKey, urlValue] = queryParam
// Check to see if url contains f[users.comma]
if (urlKey.includes('f[')) {
urlObj.set(urlKey, encodeURI(urlValue))
}
}
return urlObj.toString() // doesn't seem to work
}
I feel like I am going offroad with my approach. I'd appreciate some help here.
Since the backend service returns an encoded or decode url
We can first decode the url from the backend service (this won't produce any exceptions if url is already encoded)
const encodedExample = `/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22` // the last param is encoded
const regularExample2 = `/demo/bigquery/order_items?fields=users.email&f[users.comma]="Abbeville, Georgia"`
const specialEncode = (url) => {
let decodedUrl = decodeURI(url);
let encodedUrl = encodeURI(decodedUrl);
// fix "f[users.comma]" because encodeURI will encode the [ and ] as well
encodedUrl = encodedUrl.replace("f%5Busers.comma%5D", "f[users.comma]")
console.log(encodedUrl);
return encodedUrl;
}
specialEncode(encodedExample); // logs and returns: /demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%252C+Georgia%22
specialEncode(regularExample2); // logs and returns: /demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%252C+Georgia%22
The code above works fine for both encoded and decoded urls

Removing query parameter using node.js not working

I am having this code to remove a query parameter from a url, but it is not working. Can you have a look please?
const url = require('url')
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
const link = url.format(obj)
console.log(link) // I was expecting the removal of query2 but it didn't happen
It logged the same url as was passed above, why query2 is not removed? Thanks
You need to remove search node from object
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
delete obj.search
const link = url.format(obj)
console.log(link)
This will return you url http://www.example.com/path?query1=val1
If you look at through the source for url module (https://github.com/defunctzombie/node-url/blob/master/url.js). You can see that
it will look at the search node first (line 413). Remove this as well, so that the query object is evaluated.
delete obj.search;
Even though you delete query2 from query object, query2 is still present in search field.
const url = require('url');
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
console.log(obj);
delete obj.query.query2
delete obj.search
console.log(obj);
const link = url.format(obj)
console.log(link)
const url = require("url")
const urlObj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete urlObj.query.query2
delete urlObj.search
const newUrl = url.format(urlObj)
console.log(newUrl) // print >> http://www.example.com/path?query1=val1

Categories

Resources