5

I've been trying to find out what this code means but I haven't had any luck even finding out where to start or what to look up.

if(!/^(https?):\/\//i.test(value))

I understand some of it so I've got the following questions.

  1. what does the "/^" do?
  2. what does the ? do?
  3. what do the "(" and ")" do around the https
  4. what does the ":" do?
  5. what does the "i" do?

If this appears to be a question without research, any guidance where to start would be great.

SharpEdge
  • 1,782
  • 1
  • 9
  • 20
P0lska
  • 421
  • 5
  • 16

2 Answers2

7

What is it

A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

This is exactly the same but maybe more clear

var patt = /^(https?):\/\//i;
if( !patt.test(value) ){
  // value DOES NOT MATCH patt!
}

What it does

In this case it checks that value doesn't start with http:// or https://

RegExp Explanation

  / //Open regexp
    ^ //Start of the string
    (  // Start of the capturing group
      https? //Match literally http or https (because s is optional "?")
    )  // End of capturing group
    :\/\/ // Match literally ://
  / // Close regexp
  i // Case-insensitive flag

Learning

SharpEdge
  • 1,782
  • 1
  • 9
  • 20
1

Might this help you

  • ^ assert position at start of the string
  • http matches the characters http literally (case insensitive)
  • s? matches the character s literally (case insensitive)
  • Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
  • : matches the character : literally
  • \/ matches the character / literally
  • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Satpal
  • 126,885
  • 12
  • 146
  • 163