0

I need some help converting this PHP regular expression to a Javascript one though I am not very familiar to regular expressions:

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
7
  • it should be the same. have you tried it? Commented Jun 29, 2013 at 15:33
  • Possible duplicate of stackoverflow.com/questions/9309349/… Commented Jun 29, 2013 at 15:34
  • 1
    @x_vi_r: that's definitely not a duplicate. Commented Jun 29, 2013 at 15:35
  • @KarolyHorvath Why not ? Commented Jun 29, 2013 at 15:36
  • 2
    sigh why yes? just because there are similar keywords in the question it doesn't mean it covers it. Commented Jun 29, 2013 at 15:36

1 Answer 1

3

While the others are correct, that using some other means to parse the function would be easier, here is how you can convert the regex.

The regex contains no advanced constructs which are not available in JavaScript or have a different meaning. Hence, you can simply use the same expression in a regex literal:

var r = /((https?|ftp)\:\/\/)?([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?([a-z0-9-.]*)\.([a-z]{2,3})(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?/;

Now regex literals don't support concatenation, and neither does JS have the x modifier which would allow you to split the expression of multiple lines. So if you want to keep the pattern in multiple parts, to comment it, you'll have to concatenate a string again and pass that string to the RegExp constructor. The catch here is that backslashes need to be doubled, because JavaScripts string compilation will swallow up each unescaped backslash (so you need to escape the backslashes for them to reach the regex engine):

var rString = "((https?|ftp)\\:\\/\\/)?"; // SCHEME
rString += "([a-z0-9+!*(),;?&=\\$_.-]+(\\:[a-z0-9+!*(),;?&=\\$_.-]+)?@)?"; // User and Pass
rString += "([a-z0-9-.]*)\\.([a-z]{2,3})"; // Host or IP
rString += "(\\:[0-9]{2,5})?"; // Port
rString += "(\\/([a-z0-9+\\$_-]\\.?)+)*\\/?"; // Path
rString += "(\\?[a-z+&\\$_.-][a-z0-9;:@&%=+\\/\\$_.-]*)?"; // GET Query
rString += "(#[a-z_.-][a-z0-9+\\$_.-]*)?"; // Anchor
var r = new RegExp(rString);

In any case, r can now be used with your favourite matching function (match on a string, or test or exec on r).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.