check if string contains url javascript code example
Example 1: Check if a JavaScript string is a URL
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~
return (res !== null)
};
var testCase1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
alert(isValidURL(testCase1));
Example 2: 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 3: javascript contains substring
var str = "We got a poop cleanup on isle 4.";
if(str.indexOf("poop") !== -1){
alert("Not again");
}
Example 4: javascript determine if string is valid url
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
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]);
}