Implementing the Queries
The search property of the URL component defines the portion of the query string. It allows one to look up the values of parameters. For instance, considering the below URL given, the search property of the URL component will be “username=val1&password=val2”. To search for the individual parameters, the URLSearchParams object’s get() method can be used.
Syntax
// The parameter username and password
// value which is pass with url.
let url = new URL("https://w3wiki.com/login?username=val1&password=val2");
console.log( url.searchParams.get('username');
console.lgo(url.serachParams.get('password');
Example 1: In this example, we will parse the URL and see different parts of the URL. We will see the pathname, port number, and protocol.
HTML
<!DOCTYPE html> < html > < head > < title >Web API URL</ title > </ head > < body style = "text-align: center;" > < h1 style = "color:green" >Welcome To GFG</ h1 > < h2 >URL details</ h2 > < h2 id = "ele" ></ h2 > </ body > < script > const url = new URL(document.location.href); document.getElementById("ele").innerHTML = '< h3 >Path Name: ' + url.pathname + '</ h3 >< h3 >Port: ' + url.port + '</ h3 >' + '< h3 > Protocol ' + url.protocol + '</ h3 >' </ script > </html |
Output:
Example 2: In this example, we change the URL component attribute, see host, hostname, and origin attribute of url component.
HTML
<!DOCTYPE html> < html > < head > < title >Web API URL</ title > </ head > < body style = "text-align: center;" > < h1 style = "color:green" >Welcome To GFG</ h1 > < p > < button onclick = "fun()" >Get host</ button > < button onclick = "fun2()" >Get hostName</ button > < button onclick = "fun3()" >Get Full URL</ button > < button onclick = "fun4()" >Get UserName</ button > </ p > < h2 id = "ele" ></ h2 > </ body > < script > const url = new URL(document.location.href); url.username = 'geeks1'; url.password = 'geek@123'; function fun() { document.getElementById('ele').innerHTML = '< h3 >Host is : ' + url.host; } function fun2() { document.getElementById('ele').innerHTML = '< h3 >Host Name is : ' + url.hostname; } function fun3() { document.getElementById('ele').innerHTML = '< h3 >Full Url is : ' + url.origin; } function fun4() { document.getElementById('ele').innerHTML = '< h3 >User Name is: ' + url.username; } </ script > </ html > |
Output:
Web API URL
The Web API URL is used to access and manipulate URLs. URL stands for Uniform Resource Locator. A URL is a unique address which is pointing to the resource. The URL is essential for making HTTP requests for making interactions with the API and for getting or sending data.
Table of Content
- Concepts and Usage
- Accessing components of URL
- URL Modifications
- Implementing the Queries
We will explore the above topics with their description and understand them with suitable examples.