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

I am looking to incorporate automatic scrolling functionality into my RSS Feed

I'm in the process of developing an RSS feed for my website. My expertise in JS/jQuery is limited, so any assistance would be greatly appreciated. After utilizing Google's Feed API and creating my own RSS Reader Widget, I realized that it lacked ...

Building conditionals in AngularJS expressions using if-then-else syntax

Is there a way to incorporate the ternary-operator (if-then-else construction) in an angularjs expression? For example, I have a function $scope.isExists(item) that should return a boolean value. I would like to do something like this: <div ng-repeater ...

Navigating through Select2 with multiple nested groups is like solving a

I'm encountering difficulties when using the Select2 plugin with different groups, as only the last group is displayed. <select name="txtConta" id="txtConta" data-placeholder="Selecione a conta"> <option value=""></option& ...

What is the reason behind taps in TypeScript only registering the first tap event?

One issue I am encountering is that only the first tap works when clicked, and subsequent taps result in an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') Here is the code I am using: https://codepen ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

The Javascript Date constructor struggles to interpret date strings in certain timezones that are not enclosed in brackets

Take a look at the examples below: new Date("Wed, 28 May 2014 09:50:06 EEST"); // Invalid Date new Date("Thu, 26 Jun 2014 09:09:27 EDT"); // OK, is parsed new Date("Wed, 28 May 2014 09:50:06 (EEST)"); // OK, is parsed new Date("Thu, 26 Jun 2014 09:09:27 ( ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

New approach of using Django to replace Ajax method

My current input elements are: <input id="country_name" type"text" /> <input id="country_id" type"text" /> I am looking to dynamically update the ID based on the country name entered in the country_name input using the onchange event. To achi ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Using jQuery to create a div that animates when scrolling

Recently, I came across this interesting code snippet: $(document).ready(function(){ $(window).scroll(function(){ if($("#1").offset().top < $(window).scrollTop()); $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fix ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

Adjust the horizontal position of a text element using CSS

I am faced with a specific challenge where I need to center the text "test" within a text tag using only CSS, without being able to directly change the HTML. <text width="13.89" height="13.89" x="291.46999999999997" y="156.55" transform= ...