Regular expression example

Simple parsing of URL

by Arnaud Buchholz

JavaScript

function output (text) {
  document.body.appendChild(document.createTextNode(text))
  document.body.appendChild(document.createElement("br"))
}

// var re = /^(https?):\/\/(\w+(?:\.\w+)*)(?::(\d+))?/;
var re = new RegExp("^(https?):\\/\\/(\\w+(?:\\.\\w+)*)(?::(\\d+))?");

[
  "https://app.mural.co/t/sapstarter8122/m/sapstarter8122/1591813339604/21b68759ddf9b2db58da3cd0da5a234207ff499c",
  "this is not an url because it does not start with http",
  "http://localhost:8000/?project=hpa\.cei\.(amp|calendar|def|mkt|planningmodels|setup|campaign)(?!\.organizer)",
  "httpssss://localhost:8000/?project=hpa\.cei\.(amp|calendar|def|mkt|planningmodels|setup|campaign)(?!\.organizer)"
].forEach(function (sTestValue) {
  var oResult = sTestValue.match(re)
  output(sTestValue)
  if (oResult) {
    output("Matching")
    output("Length: " + oResult.length)
    for (var index = 0; index < oResult.length; ++index) {
      output("[" + index + "]: " + oResult[index])
    }
    sTestValue.replace(re, function (sMatchingString, sProtocol, sHostName, sPort) {
      output(sProtocol + "://" + sHostName + ":" + sPort)
    })
    
  } else {
    output("Not matching")
  }
  output("")
})