Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript检查字符串中是否有url_Javascript_Regex - Fatal编程技术网

使用javascript检查字符串中是否有url

使用javascript检查字符串中是否有url,javascript,regex,Javascript,Regex,我想使用javascript检查字符串是否包含url我从google获得了这段代码 if(new RegExp("[a-zA-Z\d]+://(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?").test(status_text)) { alert("url inside"); } 但是这一个只适用于像和这样的url,但它不适用于。我还想从字符串中提取该url,以便处理该url。试试

我想使用javascript检查字符串是否包含url我从google获得了这段代码

        if(new RegExp("[a-zA-Z\d]+://(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?").test(status_text)) {
          alert("url inside");
        }
但是这一个只适用于像和这样的url,但它不适用于。我还想从字符串中提取该url,以便处理该url。

试试这一个

(?<http>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)
(?(http:[/][/]| www.)([a-z]|[a-z]|[0-9]|[/.]|[~])*)

您可以修改正则表达式以有条件地匹配URL的方案,如下所示:

var urlCheck = new RegExp('([a-zA-Z\d]+://)?(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?', 'i')
if (urlCheck.test(status_text) {
    console.log(urlCheck.exec(status_text));
}
尝试:

Sudhir的答案(对我来说)超过了url的末尾

var str = " some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site."
var urlRE= new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+");
str.match(urlRE)
这里是我的正则表达式,以防止匹配超过url的结尾

var str = " some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site."
var urlRE= new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+");
str.match(urlRE)
使用node.js生成此输出:

[ 'http://www.loopdeloop.org/index.html',
'http://',
 undefined,
'www.loopdeloop.org',
 undefined,
'l',
index: 11,
input: ' some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site.' ]

我不认为单独匹配
www
在这里是真正必要的。可能重复@Pumbaa80:不,我的问题有点不同,我的输入可以是纯字符串,只有url,或者文本和url一起。这个可以工作,但我试着在完全键入后检查它,我的意思是……当我键入“”此条件满足并显示警报…我希望此脚本等待用户输入完整的url,然后仅显示警报…通过我使用keyup事件进行检查的方式。@AmitPail使用文本框的模糊事件,而不是keyup,sudhir的答案似乎无法提取该url,顺便说一句。您可以使用模糊事件,所以一旦焦点从文本框中消失,你就可以运行代码了……是的,这是我最后能想到的技巧,但我想在keyup事件中使用它的原因是……每当我检测到url时,我想启动ajax调用来提取url的详细信息,同时用户可以继续键入……就像在facebook状态下一样
[ 'http://www.loopdeloop.org/index.html',
'http://',
 undefined,
'www.loopdeloop.org',
 undefined,
'l',
index: 11,
input: ' some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site.' ]