正则表达式为http://但不是https://

时间:2016-10-04 16:28:47

标签: javascript regex

我需要标记包含以http://开头但不包含https://的网址的文字区域。我认为这应该有效,但即使所有网址都是https,我也会收到提醒。

$('#template_form').submit(function() {
    alert("this is the text: " + $("#template_data").val() );
    val = $("#template_data").val();
    if (val.search(/^http:\/\//)){
        alert("there's a URL in there...");
        return false;
    }
    return true;
});

<textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>

如果网址为http://www.test.com,此 只会显示第二个提醒,但它会按https://的方式将其丢弃。我做错了什么?

3 个答案:

答案 0 :(得分:1)

来自search()的文档:

  

一种String方法,用于测试字符串中的匹配项。它返回匹配的索引,如果搜索失败则返回-1。

-1会将if语句评估为true(if (-1) {alert("true");}。所以要么切换到match()test(),要么检查if (val.search(...) > -1)

同样,^在你的正则表达式中是错误的,它只会从字符串的开头匹配。

$('#template_form').submit(function() {
  alert("this is the text: " + $("#template_data").val());
  val = $("#template_data").val();
  if (val.match(/http:\/\//)) {
    alert("there's a URL in there...");
    return false;
  }
  return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="template_form">
  <textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>
  <input type="submit" value="submit">
</form>

答案 1 :(得分:0)

String.search()不是布尔值:

  

返回值
  正则表达式和给定字符串之间的第一个匹配的索引;如果没有找到,-1。

此外,在同一份文件中:

  

当你想知道是否找到一个模式以及它的索引时   字符串使用search(),如果您只想知道它存在,请使用   类似test()方法,返回布尔值

答案 2 :(得分:0)

$('#template_form').submit(function() {
  if ($("#template_data").val().indexOf("http:\/\/") > -1) {
    return false;
  }
  return true;
});

这是另一种方式。