How to check if a URL contains a given string using jQuery

jQuery - Write Less Do More

jQuery – Write Less Do More

I used to use regular expressions to check for loads of things pre jQuery. I still do use regular expressions for other things though. In a few cases “there is no school like the old school”. But the great thing about jQuery now is the checking if a URL contains a given string is piece of cake.

Give us a real world instance I hear you say. OK let’s say you are working with the C-Sharp Razor programming language and want to be able check quickly for a series of strings within a URL at different stages of a UX journey. however you didn’t want to have to compile a Model or two, a CS file and yet another CSHTML file. Let’s just say (well I can say because it happened to me!);

The jQuery(actually it’s JavaScript)

$(document).ready(function () {
    if(window.location.href.indexOf("registered") > -1) {
       alert("Congratulations you are now a member!");
    }
});

Developer Note = even if the index is not found, it will return -1, in which case the if condition will pass and execute; using this method, you should explicitly check that .indexOf(‘registered’) > 0. Generally speaking you should search strings with > -1 or >= 0.

Another assumption made here is that you already have the jQuery framework plugged into your web app, otherwise it would be a waste really to reference the jQuery framework just to run a few lines of code.

In the real world you are not going to throw an alert box at your user, that is not unobtrusive! The larger function that this small script may be part of will be using a variable you’ve set within this function as trigger to set off another function.

3 Comments

  1. Gatzby says:

    What does jQuery have to do with any of this? The whole point of your story, checking if the URL contains a certain string, is done entirely without jQuery. The indexOf method is native JavaScript. Are you really going to load several kilobytes of jQuery to do something as trivial as this?

    Remember: jQuery == JavaScript.

  2. Robert Price says:

    Hi,

    I’m not sure if I’ve misunderstood you, but using the .indexOf method isn’t jQuery specific, but something that’s been part of JavaScript since version 1.0.

    If the substring exists, then it’s position in the string is returned – the first position being 0 like the first element of an array. If no occurance of the substring is found then -1 is returned.

    Your example code looks correct, but the Developer Note below it is ambiguous.

    If the code is going to be frequently run in a tight loop, then a slight performance increase could be to use an inverted identity comparison !== -1 rather than > -1.

Leave a Reply

Your email address will not be published. Required fields are marked *