2

I want to test my urls validity , which should start with http:// or https:// ,

i ve used this RegExp :

private testIfValidURL(str) {
    const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
      '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
    return !!pattern.test(str);
  }

This would work , execpt one case :

To consider it as valid , my urls should always start with http:// or https:// , but with my function , urls like www.abcd.com would be treated as valid urls which is not enough for me.

Sugesstions ?

1
  • What is a "valid" url for you? Commented Mar 14, 2019 at 12:52

2 Answers 2

1

Just change ^(https?:\\/\\/)?' to ^(https?:\\/\\/)', the ? means that you want to match zero or one occurnece of a pattern. You actually want exactly one occurence, so don't use ? :)

From regular-expressions:

? - Makes the preceding item optional. Greedy, so the optional item is included in the match if possible.

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

Comments

1

You can remove the (...)? chars, so it will be mandatory to have a http or https sequence first.

function testIfValidURL(str) {
  const pattern = new RegExp('^https?:\\/\\/' + // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
    '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator

  return !!pattern.test(str);
}

console.log(testIfValidURL('www.abcd.com'));
console.log(testIfValidURL('http://www.abcd.com'));
console.log(testIfValidURL('https://www.abcd.com'));
console.log(testIfValidURL('htt://www.abcd.com'));

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.