check if string is url javascript code example
Example 1: url validator javascript
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+
'((\\d{1,3}\\.){3}\\d{1,3}))'+
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
'(\\?[;&a-z\\d%_.~+=-]*)?'+
'(\\#[-a-z\\d_]*)?$','i');
return !!pattern.test(str);
}
Example 2: Check if a JavaScript string is a URL
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
return (res !== null)
};
var testCase1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
alert(isValidURL(testCase1));
Example 3: check if url contains string
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
}
});
</script>
Example 4: js check if url
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
return (res !== null)
};
var testCase1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
console.log(isValidURL(testCase1));
var testCase2 = "http://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&docid=nIv5rk2GyP3hXM&tbnid=isiOkMe3nCtexM:&ved=0CAUQjRw&url=http%3A%2F%2Fanimalcrossing.wikia.com%2Fwiki%2FLion&ei=ygZXU_2fGKbMsQTf4YLgAQ&bvm=bv.65177938,d.aWc&psig=AFQjCNEpBfKnal9kU7Zu4n7RnEt2nerN4g&ust=1398298682009707";
console.log(isValidURL(testCase2));
var testCase3 = "https://sdfasd";
console.log(isValidURL(testCase3));
var testCase4 = "dfdsfdsfdfdsfsdfs";
console.log(isValidURL(testCase4));
var testCase5 = "magnet:?xt=urn:btih:123";
console.log(isValidURL(testCase5));
var testCase6 = "https://stackoverflow.com/";
console.log(isValidURL(testCase6));
var testCase7 = "https://w";
console.log(isValidURL(testCase7));
var testCase8 = "https://sdfasdp.ppppppppppp";
console.log(isValidURL(testCase8));
Example 5: check if string contains url
var reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
if (reg.test(status_text)) {
alert(reg.exec(status_text)[2]);
}