Query string values in JavaScript

In this quick code you will learn how to get query string (browser address bar's variable) values using JavaScript.

To do such tasks and JavaScript itself enough to make your job done. Let's try out how this works.

<script>
    (function () {
        // we can call getQueryStringByName from anywhere we want
        var result = getQueryStringByName('id');
        alert(result);
    })();

    function getQueryStringByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
</script>

If you run above code and URL contains 'id' as query string, then its values will be alerted, here is screenshot.


Hope this helps.

Comments

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples