Tuesday, February 7, 2023

Convert URLSearchParams to a JavaScript Object | JavaScript jQuery Get Parameters from URL | Get Params from URL using JavaScript

Use the Object.fromEntries method and pass the URLSearchParams instance as an argument. This creates a JavaScript object from the parsed query parameters:
const params = Object.fromEntries(  
  new URLSearchParams(window.location.search)
)

// URL: example.com/path?foo=bar&name=futurestudio&num=1
// { foo: 'bar', name: 'futurestudio', num: '1' }
Here’s how it works: the URLSearchParams class implements JavaScript’s iterator interface. The iterator interface contains the Iterator#entries method. This entries methods returns an iterator providing an array of [key, value] pairs:
const params = new URLSearchParams('?foo=bar&name=futurestudio&num=1')

const iterator = params.entries()

iterator.next()  
// { done: false, value: ['foo', 'bar'] } 

iterator.next()  
// { done: false, value: ['name', 'futurestudio'] } 

iterator.next()  
// { done: false, value: ['num', '1] } 

iterator.next()  
// { done: true, value: undefined } 

How to Get URL Parameters with JavaScript

URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more.
In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
We can then parse the query string’s parameters using URLSearchParams:
const urlParams = new URLSearchParams(queryString);
Then we call any of its methods on the result.

For example, URLSearchParams.get() will return the first value associated with the given search parameter:
const product = urlParams.get('product')
console.log(product);
// shirt

const color = urlParams.get('color')
console.log(color);
// blue

const newUser = urlParams.get('newuser')
console.log(newUser);
// empty string
Use the Object.fromEntries method and pass the URLSearchParams instance as an argument. This creates a JavaScript object from the parsed query parameters:

const params = Object.fromEntries(  
  new URLSearchParams(window.location.search)
)

// URL: example.com/path?foo=bar&name=futurestudio&num=1
// { foo: 'bar', name: 'futurestudio', num: '1' }
Checking for the Presence of a Parameter

You can use URLSearchParams.has() to check whether a certain parameter exists:
console.log(urlParams.has('product'));
// true

console.log(urlParams.has('paymentmethod'));
// false
Getting All of a Parameter’s Values

You can use URLSearchParams.getAll() to return all of the values associated with a particular parameter:
console.log(urlParams.getAll('size'));
// [ 'm' ]

//Programmatically add a second size parameter.
urlParams.append('size', 'xl');

console.log(urlParams.getAll('size'));
// [ 'm', 'xl' ]
Iterating over Parameters

URLSearchParams also provides some familiar Object iterator methods, allowing you iterate over its keys, values and entries:
const
  keys = urlParams.keys(),
  values = urlParams.values(),
  entries = urlParams.entries();

for (const key of keys) console.log(key);
// product, color, newuser, size

for (const value of values) console.log(value);
// shirt, blue, , m

for(const entry of entries) {
  console.log(`${entry[0]}: ${entry[1]}`);
}
// product: shirt
// color: blue
// newuser:
// size: m

Monday, February 6, 2023

Prevent scroll position of window when focus on LeafLet Map - Mouse wheel zoom on leaflet map only after click - Leaflet map scrolls top on focus on Browsers

I have a leaflet map on an HTML page. When the map is focused the map jumps so that it's completely visible in the viewport. If the whole map doesn't fit, then the top of the map becomes aligned with the top of the viewport and the bottom just hangs off the end.
This is annoying, because then the whole page area jumped to top.
We need to add the listener immediately after the map initialized. So the whole thing becomes normal as we want like no scroll on focus.
const map = L.map('leaflet-js-map').setView([latLng[0].Longitude, latLng[0].Latitude], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    minZoom: 10,
    maxZoom: 18,
    attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
}).addTo(map);

map.once('focus', function(e) {
    console.log(e);
    if (map.scrollWheelZoom.enabled()) {
        map.scrollWheelZoom.disable();
    }
    else {
        map.scrollWheelZoom.enable();
    }
});

Monday, January 16, 2023

Few Tools That I Badly Need In My Daily Life


Wednesday, January 11, 2023

How to Use .gitconfig's includeIf - Git 2.13 conditional config on windows - git set username and email for separate project - Is it possible to have different Git configuration for different projects?

.gitconfig is usually stored in the user.home directory.
I use a different identity to work on projects for Company A and something else for Company B (primarily the name / email). How can I have two different Git configurations so that my check-ins don't go with the name / email?
As of git version 2.13, git supports conditional configuration includes. In this example we clone Company A's repos in global directory anywhere in my computer, and Company B's repos in some other specific folder like D:/Mine/Projects. For company B, we will keep all our repo's inside D:/Mine/Projects
File Location For Windows : "C:\Users\${USER_NAME}\.gitconfig", follow below steps to make it work:
  • Open .gifconfig in a editor
  • Paste below contents as example:
    [include]
      path = .gituser-default
    [includeIf "gitdir:D:/Mine/Projects/"]
      path = .gituser-company-b	
    [credential]
    	helper = wincred
    
  • Now edit .gituser-default with below contents - this configuration will use for anywhere in your computer
    [user]
    	name = Pritom Kumar
    	email = pritomkucse@gmail.com
    
  • Now edit .gituser-company-b with below contents - this configuration will use for Company B
    [user]
    	name = Pritom Kumar
    	email = pritomku.test@gmail.com
    
  • Now clone an repo into the /D/Mine/Projects directory and navigate to the project directory
  • Now run command git config user.email to check the configuration, you will see as below:

How to fix - git@github.com permission denied (publickey). fatal could not read from remote repository and Support for password authentication was removed. Please use a personal access token instead - Git: How to solve Permission denied (publickey) error when using Git - Fix "Permission denied (publickey)" error when pushing with Git

So, the problem arised when I tried to clone a Git repository from github using below command:
git clone git@github.com:user-name/repo-name.git

But I failed with below error:

Cloning into 'repo-name'...
The authenticity of host 'github.com (20.205.243.166)' can't be established.
ECDSA key fingerprint is SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,20.205.243.166' (ECDSA) to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Possible solution is Create SSH key pair
The process is as below:
1. Open Git Bash and run command ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
2. Accepts the default file location (using Enter key)
3. Set SSH key passphrases or hit Enter button twice - will generate private and public key.
4. Your identification has been saved in /c/Users/user-name/.ssh/id_rsa... if you don't change location.
5. Copy the SSH key to your clipboard using command clip < /c/Users/HP/.ssh/id_rsa.pub.
6. Time to set key to github account, go to https://github.com/settings/profile
7. Then go to SSH and GPG keys and click on New SSH key button and paste SSH key to the big text box (Make sure you remove your email address from SSH key at end):
8. You are done from github end.
9. Now you can clone your GitHub repo and it will not complain about git@github.com permission denied (publickey). fatal could not read from remote repository
10. It's time to try again to clone repo using Git Bash.
11. Execute command git clone git@github.com:user-name/repo-name.git and let's see what happen
12. So it's done, repo clonned successfully:
Benefits of this approach
  • You do not need to supply your GitHub Username and password
  • More secured way to connect with GitHub
Drawback
  • The process of generating SSH keys is little troublesome
  • If you switch your laptop/desktop then you need re-generate the SSH keys again and perform the same steps onto your new laptop/desktop