How to check if the URL contains a given string?

How to check if the URL contains a given string?

How could I do something like this:


Solution 1:

You need add href property and check indexOf instead of contains

<script src=""></script>
<script type="text/javascript">
  $(document).ready(function() {
    if (window.location.href.indexOf("franky") > -1) {
      alert("your url contains the name franky");

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){....}

Solution 4:

like so:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
                 alert("your url contains the name franky");

Solution 5:

window.location isn’t a String, but it has a toString() method. So you can do it like this:




From the old Mozilla docs:

Location objects have a toString
method returning the current URL. You
can also assign a string to
window.location. This means that you
can work with window.location as if it
were a string in most cases.
Sometimes, for example when you need
to call a String method on it, you
have to explicitly call toString.

Solution 6:

The regex way:

var matches = !!location.href.match(/franky/); //a boolean value now

Or in a simple statement you could use:

if (location.href.match(/franky/)) {

I use this to test whether the website is running locally or on a server:


This checks whether the href contains either 192.168 or localhost AND is followed by :1337.

As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.