10

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.

2

5 Answers 5

26

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");
}
Sign up to request clarification or add additional context in comments.

4 Comments

This one works, But i am trying to check it once its compltely typed i mean...when i type "go" this condition satisfies and shows alert...i want this script to wait until user enters complete url and then only show alert...by the way i m using keyup event to check.
@AmitPatil use blur event of the textbox, instead of keyup, sudhir's answer seems not extract that url, btw.
you can use blur event, so that once focus is lost from the textbox you can runs the code...
Yes thats the trick i can think of at last, but the reason i want it on keyup event is that...whenever i detect url i want to fire ajax call to extract details of the url in the meantime user can continue his typing...like it works on facebook status
3

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.' ]

Comments

1

You can modify the regex to conditionally match on the scheme of the URL, like so:

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));
}

Comments

1
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]);
}

Comments

0

try this one

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

1 Comment

I don't think that matching the www seperately is really necessary here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.