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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!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
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!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> |