Home > Mobile >  Why maybe url.length != 0 cause problem if no match is found in javascript?
Why maybe url.length != 0 cause problem if no match is found in javascript?

Time:12-29

When I click "Open Windows" button in Code A, the two links can be opened in two tabs at one time in Chrome as I expected.

I append a blank line in textarea control in Code B, I find only a link http://www.google.com/ can be opened, why?

It seems that if (url.length != 0) {...} maybe cause problem, I'm not sure.

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

CodePudding user response:

When there's no match .match() returns null, so you can't access the first element with [0]. You have to check for this.

You can use optional chaining to avoid lots of extra coding.

        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);
                }
            });
        }
  • Related