What issues can arise in JavaScript if the URL length is not zero when there is no match found?

Upon clicking the "Open Windows" button in Code A, I expected the two links to open in two tabs simultaneously in Chrome, which is exactly what happened.

However, when I added a blank line in the textarea control in Code B, only the link http://www.google.com/ was able to be opened. Why is this happening?

I suspect that the condition if (url.length != 0) {...} might be causing the issue, but I'm not certain.

Code A

<html>
<head>
    <script src="Js/jquery-3.6.3.min.js"></script>

    <script type="text/javascript">

        function open_win() {
            let links = $('#textID').val();
          
            if (links) {
                let row = links.split('\n');
                row.forEach((original_url) => {                    
                    var url = original_url.match(/\b(http|https)?:\/\/\S+/gi)[0];
                    if (url.length != 0) {
                        window.open(url);
                    }
                });
            }
        }

    </script>
</head>

<body>

    <textarea id="textID" name="message" rows="10" cols="80">
     AAA   http://www.google.com/          
     http://www.msn.com/  BBB
    </textarea>

    <br />
    <input type=button value="Open Windows" onclick="open_win()">

</body>

</html>

Code B

//Same
<textarea id="textID" name="message" rows="10" cols="80">
     AAA   http://www.google.com/          

     http://www.msn.com/  BBB
    </textarea>
//Same

Answer №1

If there is no match found, the .match() function will return null, meaning you cannot access the first element using [0]. It's important to check for this condition before proceeding.

To streamline your code and avoid unnecessary complexity, you can make use of optional chaining.

        if (links) {
            let row = links.split('\n');
            row.forEach((original_url) => {                    
                var url = original_url.match(/\b(http|https)?:\/\/\S+/gi)?.[0];
                if (url) {
                    window.open(url);
                }
            });
        }

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

Navigating to a Specific Section with a Fixed Header on Another Page

Trying to create a link to an anchor on Page 1 from Page 2, both of which have fixed headers. I'm utilizing the following script on both pages: $(document).ready(function(){ $('.testlink').bind('click', function(e) { e ...

The interactive div element doesn't function properly with the mouseover feature

When my mouse over feature is active, the clickable image fails to send the value to my text file. However, if I change the div tag to (this), then the value is successfully sent but the mouse over function stops working. This occurs when the mouse over f ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Issue encountered while executing npm command: "Module 'npmlog' not found"

Today marks the beginning of my first job, and as I was setting up my development environment on my Mac (OSX) by updating node and npm, something went awry. Whenever I attempt to use npm in my command line (npm init, npm install, etc.), I am confronted wit ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

Ensure the accordion is fully loaded before initializing by checking if it has been loaded before using the .html() method

One issue I am facing is that the accordion html is being injected onto a tag using .html() before the accordion initialization, resulting in the injected html appearing as plain html. Below is my script: $(function() { $( "#accordion1" ).accordion({ ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

Using JS and d3.js to eliminate or combine duplicate connections in a d3.js node diagram

Hey there! Hello, I am new to working with js/d3.js and tackling a small project. Here are some of my previous inquiries: D3.js: Dynamically create source and target based on identical JSON values JS / d3.js: Steps for highlighting adjacent links My cu ...

Troubleshooting: How to Fix Missing Sum Display in HTML Input Fields

I am new to the world of website programming and I am currently working on creating a basic sum equation using two input fields from the client-side. <!DOCTYPE html> <html> <head> </head> ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

IDEA 2021.2 NPM SCRIPTS: Looks like there are no scripts available

Searching through the npm scripts, I am unable to locate any, however package.json does contain: ...

Using jQuery to harness the power of a single event for multiple controls

Looking to condense some code here, let me explain further. I currently have multiple Button controls each with individual click events assigned to them. $(".button").click(function() { var v1 = $(this).attr('id'); switch(v1) { ...

Tips for implementing an autoscroll feature in the comments section when there is an abundance of comments

Having a large number of comments on a single post can make my page heavy and long sometimes. This is the current layout of my post comment system: Post 1 Comment for post 1 //if comments are more than 3 <button class="view_comments" data-id="1">Vi ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

Creating a choppy movement when switching between content with jQuery

I am experiencing a choppy effect when trying to toggle the content visibility with a button click. Can someone advise if there are any issues in how I have structured the markup? Also, is there a way to achieve a smoother toggle effect? View Code $(do ...

Do I need to provide my email and password while using the Firebase signInWithGoogle()?

After attaching the signInWithGoogle() method to a button within the form, instead of opening a popup window as expected, it prompts me to fill in the email and password fields. Below is the configuration file: import firebase from 'firebase/app' ...

Passing variables with AngularJS and Typescript using a service

Currently in the process of developing an application using AngularJS, I am faced with the challenge of passing a URL when clicking on a menu button in order to utilize that URL within an iframe on another view controlled by a separate controller. Despite ...

Utilize the diff2html jQuery plugin seamlessly within an Angular directive while avoiding conflicts

I'm attempting to style a diff within an Angular directive using diff2html and var jq = $.noConflict(); I have set up an Angular constant to store jQuery and then passed it into the directive like this: app.js (function () { //IIFE to activate stri ...

When uploading a file using the file input in a table row, the text input will only appear in the first row and not in

I have a new application available for testing: VIEW APPLICATION Kindly follow the steps outlined below: Click the Add Question button twice to add 2 file inputs to the table below: Using the file input in TABLE ROW 1, upload 2 images (one at a time ...