applecrusher applecrusher - 1 month ago 12
Javascript Question

Matching Regular Expression for URLS in JavaScript Produces null

I have the following regular expression which I have validated:

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


enter image description here

I have the following Javascript code to find regular expressions:

var cTextVal = "This URL should match http://google.com";
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

Escape forward slashes before second capture group

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

var cTextVal = "This URL should match http://google.com";

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

console.log(matches);