1

I am trying to write a regular expression to return true for the following cases:

  1. http://anything
  2. http:///anything (It can have any number of "/")

But, it should return false for the following cases:

  1. http://
  2. http:/
  3. http:
  4. http
  5. htt
  6. ht
  7. h
  8. http:/// (It can have any number of "/")

I tried the following, but it fails in some cases. Can anyone give some pointers.

(/^(f|ht)tps?:\/\//i.test(jQuery("base").attr("href")

2 Answers 2

4

You can use this regex:

^(?:f|ht)tps?:\/{2,}[^\/].*
  • \/{2,} will match 2 or more / in your input.

  • [^\/].* after \/{2,} will make sure that input doesn't end with http:// or https:///.

RegEx Demo

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

2 Comments

You're right. Check my updated answer and demo link.
Thanks a ton !!! works like a charm and thanks for the explanations for better understanding !!!
0

var input = document.getElementById("input");
var output = document.getElementById("output");

var re = new RegExp("http://+[^/\\s][^\\s]*","g");

// To test a single do
// re.test(string)

output.innerHTML = input.innerHTML.match(re).join("\n");
#output {
  background-color:#EEF5F9;
  padding:10px;
}
h2 {
  margin:0;
  padding:0;
  font-size:medium;
  font-family:sans-serif;
}
pre {
  margin:0;
  padding:0 10px 0 0;
}
<h2>Inputs</h2>
<pre id="input">
    http://foo
    http:///bar
    http://foo-bar/baz
    http://
    http:/
    http:
    http
    htt
    ht
    h
    http:/// (It can have any number of "/")
</pre>

<h2>Matched</h2>
<pre id="output"></pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.