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.
Its really helpful
ReplyDelete