I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://.
Here is the regular expression (RegExp) I have been using:
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);
}
Although this function works in most cases, there is one exception:
For a URL to be considered valid, it must always begin with http://
or https://
. However, my current function validates URLs like www.abcd.com
, which is not ideal for me.
Any suggestions?