How to Validate Website URL and Manipulate URL Fields Using Javascript Full Tutorial For Beginners

How to Validate Website URL and Manipulate URL Fields Using Javascript Full Tutorial For Beginners

 

Welcome folks today in this post we will be validating website url and manipulating website fields in javascript. All the source code of the application is given below.

 

 

 

Get Started

 

 

 

In order to get started we need to create an index.html file and copy paste the following code

 

index.html

 

First of all we will look on how to do website url validation in pure javascript

 

<!DOCTYPE html>
<html>
  <head>
    <title>URL Validator and Manipulator in Javascript</title>
  </head>
  <body></body>
  <script>
    try {
  const url = new URL('http ://freemediatools.com');
  console.log("it is correct domain")
} catch (error) {
  console.log(error); // => TypeError, "Failed to construct URL: Invalid URL"
}
  </script>
</html>

 

 

 

Here as you can see in the above section of code we are using the url constructor to pass the website url which is not correct in syntax. Here we are using the try catch block to catch any sort of error which takes place during execution. If you execute this file inside the browser you will see this error as shown below

See also  Build a Coronavirus COVID-19 Live Data Map Tracker Using Google Maps API in Browser Using Vanilla Javascript Full Project For Beginners

 

 

 

As you can see in the above figure in the console it is saying invalid url

 

And now we will be seeing when the url is correct like this

 

<!DOCTYPE html>
<html>
  <head>
    <title>URL Validator and Manipulator in Javascript</title>
  </head>
  <body></body>
  <script>
    try {
  const url = new URL('https://freemediatools.com');
  console.log("it is correct domain")
} catch (error) {
  console.log(error); // => TypeError, "Failed to construct URL: Invalid URL"
}
  </script>
</html>

 

 

 

 

As you can see in the above figure it is saying it is correct domain.

 

Now we will see how to manipulate website url fields by using this block of code

 

<!DOCTYPE html>
<html>
  <head>
    <title>URL Validator and Manipulator in Javascript</title>
  </head>
  <body></body>
  <script>
    const url = new URL("https://freemediatools.com");

    console.log("the old domain is " + url.href);

    url.hostname = "codingshiksha.com";

    console.log("the changed doamin is " + url.href);
  </script>
</html>

 

See also  Build (Amazon,Flipkart) Product Discount Percentage Calculator Tool in Browser Using HTML5 & Javascript Full Project For Beginners

 

Leave a Reply