JavaScript saves all URLs using a consistent format (http, https, www.)

As a junior backend developer, my experience with JavaScript is limited. I am attempting to standardize the format of stored URLs as shown below:

www.hello.com
hello.com
http://hello.com
https://hello.com

Currently, if I input hello.com, it automatically converts to http://www.hello.com, which is great!

However, I am struggling to modify this function to also convert www.hello.com to http://www.hello.com.

My issue now is that it results in http://www.www.hello.com. There must be a way to remove the extra www or adjust the function slightly?

        function checkURL(abc){
            var string = abc.value
            if(!(/^http:\/\//.test(string))){
                string = "http://www." + string;
            }

            abc.value=string

}

edit

The main problem I'm facing is on the backend (as a Python/Django developer) where I use the URL as part of a POST request in a user form. I aim to store all URLs in a consistent format for easy comparison and matching purposes. Therefore, whether a URL is entered as hello.com, www.hello.com, or even http://hello.com, I want them all saved in the same format for reliable company matching when querying the database. I believe using a JavaScript function is the most suitable solution here. While I don't necessarily need the www prefix, consistency in formatting is crucial.

Answer №1

Here is a potential solution for your query:

/**
  @param str = URL to be parsed
  @param options = can contain "withHttp", "withHttps" or "withWWW" booleans
**/

const parseUrl = (str = '', options = {}) => {
  const [tld, domain, ...sub] = str.replace(/https?\:\/\//gi, '').split('.').reverse();

  const protocol = (options.withHttp || options.withHttps) ? (options.withHttps) ? 'https://' : 'http://' : '';
  const subDomain = (options.withWWW) ? 'www.' : (sub.length) ? `${sub}.` : '';

  return `${protocol}${subDomain}${domain}.${tld}`;
};

console.log(parseUrl('hello.com', {withHttps: true, withWWW: true}) === 'https://www.hello.com');

The concept here is that the default behavior removes only the http/https protocol and retains the subdomain.domain.tld structure. However, using options allows you to customize the final output based on the input.

If you wish to exclude the subdomain (or "www."), then you could enhance the functionality of parseUrl accordingly.

Feel free to experiment and enhance it as needed, but this should serve the purpose in relation to your original question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

Efficient page navigation bar that doesn't clutter the layout

I'm facing an issue with my navbar setup. I want it to stay at the top of the page without being sticky. However, the presence of the navbar is causing a scroll to appear on my page. This happens because: The navbar takes up space I sometimes use tri ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Troubleshooting: Why jQuery is Not Functioning Properly in Conjunction

Currently, I am in the process of developing a friend search feature. This function operates effectively; upon entering a name in the search bar, individual user profiles appear in separate div containers with their respective images and names. Each profil ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...

Encountering an Enumeration Exception when trying to delete an element from a collection list using a foreach loop

I encountered an issue when attempting to remove an element from a list collection using foreach. I have searched online but have not found a clear explanation for the problem. If anyone has knowledge about this, please share the information. ...

Customer is unable to locate the "InitializeAuthenticationService" function

After launching my application, the browser console keeps showing me three errors that all say Could not find 'AuthenticationService.init' ('AuthenticationService' was undefined). and Microsoft.JSInterop.JSException: Could not find &apo ...

Using NodeJS in conjunction with Nginx

Running both NodeJS and Nginx on the same server has posed a unique challenge for me. I have successfully configured Nginx to handle requests from "www.example.com" while also wanting NodeJS to take requests from "api.example.com". The setup is almost comp ...

Issue with Braintree Integration - custom form failing to generate nonce

When I followed the code in the documentation, the nonce did not appear at the server side and I couldn't find any hidden input field for the nonce being submitted. I was only able to make it work with the drop-in form and could see the nonce on the ...

Having trouble installing Bootstrap using the `npm i bootstrap` command? It seems like the

The npm i bootstrap command is not working when trying to install Bootstrap. Nothing is being added to the packages.json file or node_modules directory. Here are the dependencies listed in the package.json file: "dependencies": { "@angu ...

Structuring React components - Incorporating a form within a modal

I am currently utilizing the react-bootstrap Modal, Form, and Button components. My goal is to have the button trigger the modal window containing a form. Once the form is filled out, clicking another button within the modal will validate the data and sen ...

The callback for AJAX was unsuccessful

Using ajax to update form data in the database, a success response is expected but it's not functioning as intended. html <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> ...

Steps for passing a Javascript variable through POST method and then redirecting to a different page

I am facing an issue with sending a JavaScript variable via POST to a PHP page and displaying the new page. Despite checking the variable using Wireshark and confirming that it is sent correctly (key and value), the new page does not show anything. $(docu ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

Having trouble with Postgres not establishing a connection with Heroku

My website is hosted on Heroku, but I keep encountering the same error message: 2018-05-06T19:28:52.212104+00:00 app[web.1]:AssertionError [ERR_ASSERTION]: false == true 2018-05-06T19:28:52.212106+00:00 app[web.1]:at Object.exports.connect (_tls_wrap.js:1 ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

What is the best way to display data retrieved from a GET request in Angular?

Spending too much time on a development issue is causing me frustration. After extensive research, I find myself stuck at this point. The problem lies in making a GET request from a service which is called by a controller. Below is the code for the servi ...

Building an object in React using JavaScript: A step-by-step guide to including all necessary fields

I am working on a Sign-up page where I console log the input values from each field when the 'Sign Up' button is clicked. However, I want to combine these individual values into one object in the console. If anyone can provide assistance with thi ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...