javascript 使用javascript检查字符串是否在字符串中的任何位置包含url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10570286/
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
check if string contains url anywhere in string using javascript
提问by www.amitpatil.me
I want to check if string contains a url using javascript i got this code from google
我想检查字符串是否包含使用 javascript 的 url 我从谷歌得到了这个代码
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");
}
But this one works only for the url like "http://www.google.com"and "http://google.com"but it doesnt work for "www.google.com".Also i want to extract that url from string so i can process that url.
但这仅适用于“http://www.google.com”和“http://google.com ”等网址,但不适用于“www.google.com”。另外我想提取该网址从字符串,所以我可以处理该网址。
回答by Sudhir Bastakoti
Try:
尝试:
if(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]+)?(/.*)?").test(status_text)) {
alert("url inside");
}
回答by N Klosterman
Sudhir's answer (for me) matches past the end of the url.
Sudhir 的答案(对我而言)匹配超过 url 的末尾。
Here is my regex to prevent matching past the end of the url.
这是我的正则表达式,以防止匹配超过 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)
produced this output using node.js:
使用 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.' ]
回答by Jesse Proulx
You can modify the regex to conditionally match on the scheme of the URL, like so:
您可以修改正则表达式以有条件地匹配 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));
}
回答by Netorica
try this one
试试这个
(?<http>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)
回答by yjshen
var reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
if (reg.test(status_text)) {
alert(reg.exec(status_text)[2]);
}