How to check if the URL contains a given string?
How could I do something like this:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
Solution 1:
You need add href property and check indexOf
instead of contains
<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>
Solution 2:
if (window.location.href.indexOf("franky") != -1)
would do it. Alternatively, you could use a regexp:
if (/franky/.test(window.location.href))
Solution 3:
You would use indexOf
like this:
if(window.location.href.indexOf("franky") != -1){....}
Also notice the addition of href
for the string otherwise you would do:
if(window.location.toString().indexOf("franky") != -1){....}