Reputation: 781
I am trying to find URL form a sting. I want to check if string contain any URL.
For that sake i wrote code :
function get_url_from_string(str) {
var searchText = str,
urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);
for (var i = 0, il = urls.length; i < il; i++) {
var ur=urls[i];
}
return ur;
}
But it returning only URL with out any parameter. For Example if i pass:
Hi Check This https://www.youtube.com/watch?v=eHOc-4D7MjY
It gives me https://www.youtube.com Only
I want to get full url. I have no idea of regular expression. Please help. Thanks
Upvotes: 1
Views: 212
Reputation: 484
function get_url_from_string(str) {
var searchText = str,
urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})?(.*)\b/ig);
for (var i = 0, il = urls.length; i < il; i++) {
var ur=urls[i];
}
alert(ur);
return ur;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="x" onclick="get_url_from_string('https://www.youtube.com/watch?v=eHOc-4D7MjY')">click here
</button>
Upvotes: 2
Reputation: 1125
Try This it works well for me.
var url_regex = /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?/gi;
var text = "some text string here!!";
var urls_array = [];
while ((urls = url_regex.exec(text)) !== null) {
urls_array.push(urls[0]);
}
This code is used in my project
Upvotes: 2
Reputation: 305
try this -
/\b(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?\s/
Upvotes: 2