bqcqON bqcqON - 10 months ago 76
Javascript Question

RegEx - URL starts with http(s)

basically I would like to check whether an URL starts with http/https or not. I am def. no expert in RegEx but I am kinda confused on why my approach is wrong.

My expression:

^(http|https):\/\/.*$


I am using RegExr to check whether my expression is working or not and it shows me that it did not match anything.

Anyone got any input for me? Damn RegEx!

Edit: This site - http://www.regexpal.com/ - states that my expression is working. :^)

Edit2: Using RegExr and adding my expression
^(http|https):\/\/.*$


While using the input:


http://regexr.com/

http://stackoverflow.com/


Does not return a match. However, wenn the input is only one link not followed by any kind of symbol (not even a space) it does work.
Does that mean that my expression is wrong?

Answer Source

To use Regex in JavaScript you can use either the RegExp constructor or wrap your Regular expression between two / characters.

And you can simplify your Regular expresion like so ^(https?) where:

^ asserts position at start of the string

1st Capturing Group (https?)

http matches the characters http literally (case sensitive)

s? matches the character s literally (case sensitive) and ? Quantifier — Matches between zero and one times

This is a working Snippet:

var str = "https://regex101.com/";
alert(str.match(/^(https?)/)[0]);

Note:

  • Here str.match(/^(https?)/) will return an array containing all the matched strings.
  • And if you want to test your Regex in a multiline text use the g global modifier with your Regex: /^(https?)/g