get URL parameter values using Javascript - javascript

I have created an application for getting the url parameter values using JavaScript, the application is working fine but the problem is that when the param key is having space then i am getting undefined
my code is as given below
script
function getParameter(paramName )
{
paramName = paramName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + paramName + "=([^&#]*)", 'i'), results = regex.exec(location.search);
return results == null ? undefined : decodeURIComponent(results[1].replace(/\+/g, " "));
}
let say the url is like
http://localhost/myapp/index.html?User Id=145&Dept=HR
call
getParameter('Dept') ===> Gives HR
getParameter('User Id') ===> Gives undefined
can anyone please tell me some solution for this

Related

Javascript regex to get param value

I'm working on a code base someone else built and the search function uses this to get the parameter from the url to place as a value to search against. I've tried re-writing it, modifiying it, and everything else possible and can't figure out what is going on with the reutrn value from the function.
Here's the function
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
console.log(name);
var regex = new RegExp("[\\?&#;]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
console.log(results);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var part = getParameterByName('part_name');
The value of location.search is ?part_number=1234&go=GO
Then in the input box part_name if I type 1234 to be the value of the passed in parameter it will only show 12. However typing in other random numbers it will sometimes show them all correctly. If I type 124 as the search param then it displays correctly as searching against 124.
Is there something wrong with one of these regex statments that could be causing this, or is this something on the server side? The PHP seems fine on the backend but I'm not savvy on the Regex used in the Javascript code.
EDIT:
A testing snippet:
function getParameterByName(loc, name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
document.getElementById("res").innerHTML += "Name: " + name + " - ";
var regex = new RegExp("[\\?&#;]" + name + "=([^&#]*)"),
results = regex.exec(loc);
document.getElementById("res").innerHTML += results + "<br/>";
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var part = getParameterByName('?part_number=1234&go=GO', 'part_number');
var part2 = getParameterByName('?part_name=12&go=GO', 'part_name');
<div id="res"/>

Get values of all the same parameter from url in jQuery

I have an url have contain two parameters.
Ex: https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc
Parameter 1: q=news
Parameter 2:q=bbc
I want to get all value have the same parameter, but I can only get value in first the parameter.
This is my code:
function getParameterByName(name, url) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&#]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Use $(location).attr('href'); and parse through the parameters yourself
what i have tried is only IDEA of how you can get all paremater.
var a="https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc"
var b= a.split("?")[1]
b.split("&")
By this technique you will get all parameter.
You need to convert this code to your required code.
The first q is in querystring, the second one is in hash. You should parse them in JavaScript:
QueryString
// the method is taken from http://stackoverflow.com/a/3855394/3971911
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
Hash
// the method is taken from http://stackoverflow.com/a/11920807/3971911
function getHashValue(key) {
return location.hash.match(new RegExp(key+'=([^&]*)'))[1];
}
Now you can use them like this:
alert(qs['q']); // news
alert(getHashValue('q')); // bbc
try this:
function getParameterByName(name, url,position) {
url=position==1?url:url.substr(url.lastIndexOf('#'));
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&#]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url='https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc';
alert(getParameterByName('q',url,1));
alert(getParameterByName('q',url,2));
Demo
Other than an exercise in coding, you're probably better off using existing code.
Something like:
https://github.com/sindresorhus/query-string
Pros:
It has tests
It's had more useful eyes cast over it (guessing here).
The people that have likely contributed to it will probably have used it.
If you find an issue with it, those people involved will have a keen interest in solving the problem as they're likely using it.
Cons:
None! :D

conditional use of indexOf function

I'm using a script that searches a URL for a query string and ignores the query if it is found. The script works, but only when there is a query string present. The error I am getting is Uncaught TypeError: Cannot call method 'indexOf' of undefined so it's obvious where the error is occuring, I'm just not sure how to solve it. I need to only execute indexOf when a query string is found, correct? How can I achieve this?
Here is the JS causing the error:
var href = jQuery(this).attr('href');
var fname = href;
var query = href.indexOf("?");
if (query !== -1) {
fname = href.substr(0, query);
}
I think to fix this I just need to conditionally execute the href.indexOf("?"); portion of the script, but all my attempts thus far have failed.
The test for "?" should work - perhaps your href is empty?
Live Demo
function getFName(link) {
var href = link.href || "no href found";
return href.split("?")[0];
}
var a = document.createElement("a");
a.href = "http://www.google.com/search?q=something";
var fname = getFName(a);
window.console && console.log(fname);
a.href = "http://www.google.com/search";
fname = getFName(a)
window.console && console.log(fname);
Just for your information, there is a search attribute of the link you can test if you must know if there was a querystring
Test the search property instead of href
var query = this.search;
var fname = query?this.href.split("?")[0]:this.href;
Check whether href is undefined before calling indexOf.
http://jsfiddle.net/dqzhz/
var url = getURL("http://www.example.com?q=1&x=2");
alert(url);
function getURL(link) {
url = document.createElement('a');
url.href = link;
return url.protocol + "//" + url.host;
}
http://api.jquery.com/attr/ :
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.
undefined.indexOf(...) will crash, but you could fall back on an empty string like this :
var query = (href || '').indexOf('?');
It means "something true or an empty string" :
undefined || '' -> ''
"" || '' -> ''
"a" || '' -> "a"
this function returns the value of a querystring or empty string if not found.
function getQueryParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/gi, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS, "i");
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/gi, " "));
}

How to access REAL querystring param in javascript with URL rewrite in place

I am trying to alert the querystring param in jquery because i need that ID on a page load so that i can create some html elements when the control is loaded. I cant seem to access the parameter as the URL rewrite in place and URL looks diff then the original one.
Original URL
www.somesite.com/camping?ProductId=2457&ism=0&cl=PURPLE
URL seen in browser
www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE
now, how do i access the ProductId querystring value in Jquery.
Jquery
$(document).ready(function () {
var param = getParameterByName("ProductId");
alert(param) // shows PURPLE as cl in URL is set to cl=PURPLE
});
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, " "));
}
EDIT:
here is the screenshot when i am trying to access the Querysting object on serverside..
Your current code is attempting to access the value from the querystring, which no longer exists as it has been rewritten on the server.
You can use a regular expression to dissect the rewritten URL, no jQuery required. Assuming your productId is always prefaced by -p and is immediately followed by .aspx, then this will work:
var url = 'www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE'
var matches = url.match(/-p(\d+)\.aspx/);
var productId = matches && matches[1];
console.log(productId); // = 2457
productId will be null if there are no matches to the regex.
Example fiddle

How to get parameter like (parameter name contains) with javascript?

i am using the following method to get parameter by name:
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, " "));
}
and i was wondering how to change it to get parameter that contains some string for example, i want to get the parameter that contains the word "document" but the whole parameter name is not "document".
please advise, thanks.
Like this?
val = location.search.match(/document.*?=([^&]*)/)[1]
Although I'd rather use a function that converts the whole query string into an object (like this one) and simply apply a filter afterwards:
params = urlParams()
ks = Object.keys(params).filter(function(k) { return k.indexOf("document") >= 0 })
if(ks)
value = params[ks[0]];
This way you can easily support multiple params (as in document1=foo&document2=bar) and avoid ugly dynamic regexp construction.
In older browsers you can use this instead of Object.keys/filter:
ks = []
for(var k in params)
if(k.indexOf("document") >= 0)
ks.push(k);
Suggestion:
function getParameterByPartialName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&][^&#]*" + name + "[^=]*=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
This however, will return only the 1st match, there might be more parameters that have a similar name. You could return an array of key-value pairs for all matches.

Categories

Resources