applecrusher applecrusher - 1 year ago 104
Javascript Question

Matching Regular Expression for URLS in JavaScript Produces null

I have the following regular expression which I have validated:


enter image description here

I have the following Javascript code to find regular expressions:

var cTextVal = "This URL should match";
var regEx = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"

var matches = cTextVal.match(regEx);
alert(matches); // This produces null

How do I find the string that matches this regular expression in JavaScript?

Update Based on Comments:

This crashes my code:

var regEx = /(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/g

This produces null:

var regEx = "/(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/g"

Answer Source

Escape forward slashes before second capture group

var regEx = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/;

var cTextVal = "This URL should match";

var matches = cTextVal.match(regEx).shift();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download