Using JavaScript to get a querystring by name
Recently, while developing a MVVM app, I found a use case for using JavaScript to get the querystring from the current page. In this particular case, the page pulls a page with a search bar, but I want to be able to link to the specific search results without requiring user interaction.
My final solution was found on Stack Overflow
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
This approach allowed me to get the id parameter elsewhere using
var id = getParameterByName("id");
Like this article?
0
Software Development Nerd