Javascript布尔值问题

Issue with Javascript boolean values

本文关键字:问题 布尔值 Javascript      更新时间:2023-09-26

我写了一个小脚本来重新创建Chrome地址栏,其中我的代码检查任何域扩展(.com、.edu等)的输入,如果找到扩展,则将布尔标志设置为true。然后,它检查标志,并根据结果打开网站或将其作为查询发送到谷歌。此外,如果它是一个网站,它会检查字符串是否包含http://和www.,如果不包含,则在使用Window.Open()打开目标之前将其添加到字符串中。

这里怎么了?

function openSite(){
     var domain_extensions = [".aero", ".asia", "...All Other Extensions...", ".zr", ".zw"];
        var isSite = false;
        var userIn = document.getElementById('in_field').value; //Retrieves Textbox code
        for (var i=0; i < domain_extensions.length; i++)
            if (userIn.search(domain_extensions[i]) !==-1)
                isSite = true;
                        //Checks against the array of extensions
        if (isSite === true){
            if (userIn.search("http://") === -1 || userIn.search("https://") === -1)
                {if(userIn.search("www.") === -1)
                    userIn = "http://www." + userIn;
                 else
                    userIn = "http://" + userIn;                        
                }
                window.open(userIn, '_blank');
                //if extension is found, open website
                        //if qualifier http:// or https:// and/or www. not found, append and open website               
            }
        else{
                var str = encodeURI("http://www.google.com/search?q=" + userIn);
                window.open(str, '_blank');
            } //Searches query for common extensions; if not found search google
    }

我认为这是使用search函数的一个问题。此函数将正则表达式作为其参数。.字符在正则表达式中是特殊的,可以匹配任何字符。

例如:

var test = "blasdfahsadfcomasdfasd";
console.log(test.search(".com")); // prints 11

.前面加一个反斜杠以覆盖此行为:

var test = "blasdfahsadfcomasdfasd";
console.log(test.search("''.com")); // prints -1

此外,如果只想在字符串末尾进行检查,请在字符串末尾添加一个$符号,如下所示:

var test = "blasdfahsadf.comasdfasd";
console.log(test.search("''.com$")); // prints -1; prints 12 w/o the $