Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string contains url anywhere in string using javascript

I want to check if string contains a url using javascript i got this code from 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");
        }

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.

like image 669
www.amitpatil.me Avatar asked May 13 '12 08:05

www.amitpatil.me


2 Answers

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");
}
like image 198
Sudhir Bastakoti Avatar answered Sep 29 '22 02:09

Sudhir Bastakoti


Sudhir's answer (for me) matches past the end of the url.

Here is my regex to prevent matching past the end of the 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:

[ '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.' ]
like image 33
N Klosterman Avatar answered Sep 29 '22 01:09

N Klosterman