Louis.CLast
Louis.CLast

Reputation: 454

How to extract only first url from text with javascript

I have this regexp

function isValidURL(text) {

        var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

        ......

    }

And text is: Please use http://google.com or if nothing was found ask your question on http://stackoverflow.com

And i need to extract only first url from text below. (http://google.com)

return as url

Upvotes: 3

Views: 1949

Answers (2)

Prashant Singh
Prashant Singh

Reputation: 3793

I think you can use this(provided u don't have :// in ur text other than the url itself) :-

var text = "Please visit http://stackoverflow.com and ask your question, or use http://google.com";

var text_split = text.split('://'); 
var text_req = text_split[1].(" "); // splitting with blank space 

var finalURL = "http://" + test_req[0];

Upvotes: 1

VisioN
VisioN

Reputation: 145388

Do you mean something like this:

var text = "Please visit http://stackoverflow.com and ask your question, or use http://google.com";

var match = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/​​​​​​​​​​​​.exec(text)​​​​​​​;

​console.log(match[0]);​

DEMO: http://jsfiddle.net/yh5Zv/

Upvotes: 2

Related Questions