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

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...

How can I display only the y-axis values and hide the default y-axis line in react-chartjs-2?

Although I have some experience with chartjs, I am struggling to figure out how to hide the default line. To clarify, I have attached an image that illustrates the issue. I would like to achieve a result similar to this example: . My goal is to make it loo ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...

Learn how to continuously update the current timestamp in PHP using jQuery or JavaScript every second

I am currently developing a PHP cart timer script that utilizes PHP along with jQuery and JavaScript. By using the set-interval function, I am able to continuously retrieve the current time-stamp in PHP. Once the first product is added to the cart, the t ...

ng-show and ng-hide toggling for the active row

I have a single table where I am implementing row hide and show functionality using Angular for editing and saving purposes. So far, everything works as expected. $scope.init=function(){ $scope.editable=true; } Now, when I click on the edit button ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...

How to set a default value in AngularJS ng-model using the value from another ng-model

One of the challenges I'm facing is transferring a value set by the user in an ng-model from one form field to another ng-model as the initial value within the same form. For example, I want the ng-init value of myModel.fieldB to be the val ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...

What is the process for converting variables from browser script to Python code?

I ran the script below in my browser webdriver.execute_script("document.getElementsByClassName('bulk_item').length") My goal is to have the number that the script returns stored in a variable called elem for easy access. However, simp ...

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

What is the method to implement timeago.js?

I've recently embarked on my journey to learn JavaScript, and it has only been two weeks since I started. As a beginner, I'm encountering some difficulties with implementing timeago from . The specific line of instruction that's giving me tr ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Check to see if my Node.js server is running in development or production mode

Lately, I've been facing a tedious task every time I deploy a node.js server to my production server. It involves changing all the IP addresses, DNS settings, usernames, and passwords for my various connections to databases and external APIs. This en ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

Retrieving data in Next.js

Exploring various techniques to retrieve information from APIs in next.js. Options include getServerSideProps, getStaticPaths, getStaticProps, Incremental Static Regeneration, and client-side rendering. If I need to send requests to the backend when a s ...

Update MYSQL table values using AJAX and jQuery, then dynamically refresh the updated values on the web page

Hey there! I am fairly new to utilizing ajax and encountering some difficulty with a fundamental concept. In my MySQL table called "users," I have various user information stored, including the balance they pledge to donate. My goal is to create a div elem ...