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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10625497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:12:55  来源:igfitidea点击:

Regex to check if http or https exists in the string

javascriptregex

提问by magicianiam

So i have this code:

所以我有这个代码:

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

This works perfectly for this:

这非常适用于此:

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

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

but not for:

但不适用于:

this is a website http://hello.comasdasd asdasdas

这是一个网站http://hello.comasdasd asdasdas

tried doing some reading but i dont where to place * ? since they will check the expression anywhere on the string according here -> http://www.regular-expressions.info/reference.html

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

thank you

谢谢你

回答by D. Strout

From the looks of it, you're just checking if http or https exists in the string. Regular expressions are a bit overkill for that purpose. Try this simple code using indexOf:

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

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

回答by Hosein Yeganloo

Try this:

尝试这个:

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

回答by aztaroth

The ^in the beginning matches the start of the string. Just remove it.

^一开始的字符串的开头匹配。只需将其删除。

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

should be

应该

var tarea_regex = /(http|https)/;

回答by web_bod

((http(s?))\://))

Plenty of ideas here : http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1

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

回答by Dan Tao

Have you tried using a word break instead of the start-of-line character?

您是否尝试过使用分词代替行首字符?

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

It seems to do what I thinkyou want. See here: http://jsfiddle.net/BejGd/

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