Is url valid or not using Regex
Is url valid or not using Regex & compare output of regex & Url() class
HTML
<ul id="result">
<li>
<span class="input"><b>Inputs</b></span>
<span class="outputBool"><b>With Url Class</b></span>
<span class="outputBool"><b>With Regex</b></span>
<span><b>Regex passed as Expected?</b></span>
</li>
</ul>
CSS
li {
margin-bottom: 15px;
}
.input {
display: inline-block;
width: 40%;
word-break: break-all;
}
.outputBool {
display: inline-block;
width: 15%;
}
JavaScript
function isValidUrl(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-zA-Z\\&\\d%_.,~+-:@=;&]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', // fragment locator
'i'
); */
/* below(referenceFromStack) regex refer:- https://stackoverflow.com/a/54620350/14344959 */
/* const referenceFromStack = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'((([a-zA-Z\\d]([a-zA-Z\\d-]{0,61}[a-zA-Z\\d])*\\.)+' + // sub-domain + domain name
'[a-zA-Z]{2,13})' + // extension
'|((\\d{1,3}\\.){3}\\d{1,3})' + // OR ip (v4) address
'|localhost)' + // OR localhost
'(\\:\\d{1,5})?' + // port
'(\\/[a-zA-Z\\&\\d%_.~+-:@]*)*' + // path
'(\\?[a-zA-Z\\&\\d%_.,~+-:@=;&]*)?' + // query string
'(\\#[-a-zA-Z&\\d_]*)?$' // fragment locator
); */
/* modified by me*/
const newModi = 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
'|localhost)' + // OR localhost
// '(\\:\\d+) + // port (one or more digits)
'(\\:\\d{1,5})?' + // port (digits limit 1 to 5)
// '(\\/[-a-z\\d%_.~+]*)*'+ // path
'(\\/[a-zA-Z\\&\\d%_.~+-:@]*)*' + // path
// '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\?[a-zA-Z\\&\\d%_.,~+-:@=;&]*)?' + // query string
// '(\\#[-a-z\\d_]*)?$', // fragment locator
'(\\#[-a-zA-Z&\\d_]*)?$', // fragment locator
);
return newModi.test(str);
}
const testLinks = [
['test', false],
['test.com', true],
['http://test.com', true],
['www.test.com', true],
['http://www.test.com', true],
['test.com/products', true],
['help.test.com',...