Satish Kumar Singh
Satish Kumar Singh

Reputation: 116

regex to check url not works

i added below regex to check if it is url:

function checkurl(url){
var regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
if(!$.trim(url).match(regex)){
        //alert("Not Valid Url");
        alert('Not Valid Url');
        return false;
}

this works for most of url but for below url it shows error:

https://www.youtube.com/watch?v=wEQi87xSIgU

Upvotes: 0

Views: 42

Answers (3)

anubhava
anubhava

Reputation: 785651

You need to add few more characters in your last character class to support query string i.e. ?, &, and =:

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([?=&\/\w \.-]*)*\/?$

RegEx Demo

Upvotes: 1

Markus Jarderot
Markus Jarderot

Reputation: 89221

It doesn't work for that URL because it has a query string (?v=wEQi87xSIgU).

Add this before $:

(\?[^#]*)?(#.*)?

This will match query strings, and hashes.

Upvotes: 1

vks
vks

Reputation: 67988

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([?=\/\w \.-]*)\/?$

                                              ^^          ^^

Try this.See demo.Added ?= to character class.Also removed *)* which would result in catastrophic backtracking.

https://regex101.com/r/wX9fR1/7

Upvotes: 2

Related Questions