Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
Louis.CLast Avatar asked Dec 28 '25 20:12

Louis.CLast


2 Answers

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/

like image 96
VisioN Avatar answered Dec 31 '25 10:12

VisioN


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];
like image 22
Prashant Singh Avatar answered Dec 31 '25 09:12

Prashant Singh