正则表达式检查字符串中是否存在 http 或 https

Regex to check if http or https exists in the string

本文关键字:http https 存在 是否 检查 字符串 正则表达式      更新时间:2023-09-26

所以我有这个代码:

function validateText(str)
{
    var tarea = str;
    var tarea_regex = /^(http|https)/;
    if(tarea_regex.test(String(tarea).toLowerCase()) == true)
    {
        $('#textVal').val('');
    }
}

这非常适合此:

https://hello.com
http://hello.com

但不适用于:

这是一个 http://hello.com Asdasd Asdasdas 的网站

尝试做一些阅读,但我不知道在哪里放置 * ? 因为他们会根据此处检查字符串上任何位置的表达式 -> http://www.regular-expressions.info/reference.html

谢谢

试试这个:

function validateText(string) {
  if(/(http(s?)):'/'//i.test(string)) {
    // do something here
  }
}

从外观上看,您只是在检查字符串中是否存在http或https。正则表达式对于这个目的来说有点矫枉过正。使用以下indexOf尝试此简单代码:

function validateText(str)
{
    var tarea = str;
    if (tarea.indexOf("http://") == 0 || tarea.indexOf("https://") == 0) {
        // do something here
    }
}
开头

^与字符串的开头匹配。只需将其删除即可。

var tarea_regex = /^(http|https)/;

应该是

var tarea_regex = /(http|https)/;
((http(s?))'://))

这里有很多想法:http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1

您是否尝试过使用换字符而不是行首字符?

var tarea_regex = /'b(http|https)/;

它似乎做了我认为你想做的事。看这里: http://jsfiddle.net/BejGd/