【问题标题】:My search "function" does not work我的搜索“功能”不起作用
【发布时间】:2014-09-08 00:39:33
【问题描述】:
 var cat = prompt("What Do You Want To Tweet??!");

 if(cat.length >= 140)
{
confirm("Sorry but your Tweet was over the 140 character limit by: " + (cat.length - 140));
confirm("You need to resubmit a Tweet that is not over the 140 Character limit");
}
else{
confirm("Success, Your Tweet has been posted!");
}
//scan for websites

if (cat.search(" www ", " http ", ".com"))
{

}
else{
confirm("We have Detected a URL in your Tweet");   
}

我的代码一直有效,直到我尝试“推特”一个网站。如果我输入 www 或 .com 作为推文,它会告诉我它检测到了一个很好的 url。但是当我输入 xxxxxx www xxxxxx(x 是其他)时,它不会检测到 url。

【问题讨论】:

  • 我什至没有阅读您的问题,除非您重新格式化代码并使其更具可读性,否则我可能不会阅读。请使用适当的缩进。
  • 我会稍微改变一下逻辑。检查这个小提琴:jsfiddle.net/8s7db3x5/1 - 基本上检查关键字 before 确认成功消息 - 另外,删除 wwwhttp 前后的空格@
  • 我也推荐阅读documentation of search。例如。它只需要一个参数,它应该是一个正则表达式。您传递的其他人(" http "".com")将被忽略。
  • 当我提交问题时,它告诉我将代码放入代码形式并缩进。但它不会让我缩进,它只会把我带到页面的底部。我只是将每行代码间隔 3 次以使其成为代码。
  • 所以如果我输入://its.bad.yo,我会直接通过。

标签: javascript search


【解决方案1】:

您可以使用 jQuery 进行更准确的搜索。 '.inArray()' 函数应该可以解决问题。

http://api.jquery.com/jquery.inarray/

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.inArray demo</title>
    <style>
        div {
            color: blue;
        }
        span {
            color: red;
        }
    </style>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div>"John" found at <span></span></div>
    <div>4 found at <span></span></div>
    <div>"Karl" not found, so <span></span></div>
    <div>"Pete" is in the array, but not at or after index 2, so <span></span></div>
    <script>
        var arr = [ 4, "Pete", 8, "John" ];
        var $spans = $( "span" );
        $spans.eq( 0 ).text( jQuery.inArray( "John", arr ) );
        $spans.eq( 1 ).text( jQuery.inArray( 4, arr ) );
        $spans.eq( 2 ).text( jQuery.inArray( "Karl", arr ) );
        $spans.eq( 3 ).text( jQuery.inArray( "Pete", arr, 2 ) );
    </script>
</body>
</html>

【讨论】:

    【解决方案2】:

    您可以尝试使用正则表达式

    var cat = prompt("What Do You Want To Tweet??!"),
        expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi,
        regex = new RegExp(expression);
    if(cat.length >= 140) {
        confirm("Sorry but your Tweet was over the 140 character limit by: " + (cat.length - 140));
        confirm("You need to resubmit a Tweet that is not over the 140 Character limit");
    }
    else{
        confirm("Success, Your Tweet has been posted!");
    }
    //scan for websites
    
    if (cat.match(regex)) {
        confirm("We have dectected a URL in your Tweet");
    }
    else{
       confirm("no URL");   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多