Trouble reading a query string in a Query String? - javascript

I have a URL in a query string value that is similar to this one:
example.com/?p1=a1&p2=a2
And I have a query sting on my website that takes the URL and redirects to a certain page. Like this:
mysite.com/?url=example.com/?p1=a1&p2=a2
But the query string is misinterpreted. How can I separate the query string in the value URL from the actual URL? I have tried encoding the question marks and ampersands, but the page is missing the content from the value URL.
EDIT:
This is how I get the URL, through a javascript:
function nameps(url) {
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}

how does the url value get passed to the javascript? That is the place you should be url-encoding the whole URL, to make
example.com/?p1=a1&p2=a2
be inputted into the javascript on your site as
example.com%2F%3Fp1%3Da1%26p2%3Da2
You will need to adjust your regex in your javascript to deal with this change in format or alternatively use a javascript url decoding function such as decodeuri .
decodeURI()
such as on your site:
function nameps(url) {
url = decodeURI(url); ///new line decodes the previously encoded URL
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
This would also involve however you pass the url value to the function above, would have to include the line :
url = encodeURI(url);
In order to correctly encode and format the address given.

I wouldn't try to get too complicated with the query string. Instead of this:
mysite.com/?url=example.com/?p1=a1&p2=a2
I would do this:
mysite.com/?url=example.com&p1=a1&p2=a2
Then I would parse it up and rebuild the secondary url from the components.
Trying to pack a query string in a query string is asking for trouble. I wouldn't waste any time trying to get it to work that way.

Related

Javascript how to remove parameter from URL sting by value?

How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);

How replace query string values using jQuery?

I have a problem , my original URL looks like this:
test.com/?manufacturer=0&body-style=0&min-price=270%2C000&max-price=780%2C000
As you can see, the min-price and max-price values in the query string is not correct due to the comma that is passed to the URL. It should be in their respective integer value like min-price=270000 and max-price=780000.
I need to convert the query string values of min-max and max-price using jQuery. I currently do not how to do this actually. But I have codes to get them from the URL and then convert them to the correct value. I just don't know how to implement them back to the URL (as new URL) using jQuery. These are my existing codes:
//Function to get value of parameter in query string
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, " "));
}
//Function to remove commas and convert to number
function convert_to_pure_number(x) {
//Remove commas
var x_withoutcommas=x.replace(/,/g,'');
//Convert to plain number
var y =parseInt( x_withoutcommas ,10);
return y;
}
var min_price_original=getParameterByName('min-price');
var max_price_original=getParameterByName('max-price');
var min_price_converted=convert_to_pure_number(min_price_original);
var max_price_converted=convert_to_pure_number(max_price_original);
Any suggestions how will I continue the above code with the additional code to put them back to the URL posted? Thanks for any help.
UPDATE
This is the process:
Form will be posted to the server--> URL will contain commas --> My new code will remove the comma --> In the query string value, correct value will be used.
Cheers.
use replace function like this :
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, " "));
}
var min_price_original=getParameterByName('min-price').replace('%2C','');
var max_price_original=getParameterByName('max-price').replace('%2C','');

How to get url params with javascript

Let's say I have the following url:
something.com/messages/username/id
How can I get the username or id?
You can use String.split for that:
var parts = window.location.href.split('/'); # => ["http:", "", "something.com", "messages", "username", "id"]
var username = parts[4];
var id = parseInt(parts[5]);
I guess you could use the window.location.href to get the URL and then string.split() the URL on /.
var urlParts = window.location.href.split("/");
var username = urlParts[4];
var id = urlParts[5];
I actually just had to deal with the other day. When you're accessing the cached version of some of our pages, the query string is actually part of the URL path. But if you're trying to avoid the cache, you use a query string.
Given one of the answers from How to get the value from the GET parameters? here's what I'm using to partially normalize access.
The router that takes the response does _.isArray() (we're built on top of backbone, so we have underscore available) and handles pulling the data out of the object or array in a different manner.
The slice at the end gets rid of the two "" since we're not using documents, just directories and our URLs start and end with /. If you're looking for document access, you should alter the slice accordingly.
var qs = function(){
if(window.location.search){
var query_string = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
})();
} else {
return window.location.pathname.split('/').slice(1, -1);
}
return query_string;
};
You could split your url on every '/' character like this:
var url = "something.com/messages/username/id";
var array = url.split('/');
// array[2] contains username and array[3] contains id

get data from url

i took a ready script from here, How to read GET data from a URL using JavaScript? and can't make it work, what im doing wrong?
here is my script:
function getUrlParam(param)
{
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
var url = decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
var param = getUrlParam("process_number");
alert(param);
and here is my link:
http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192
thx for the help!
Sorry guys, forgot to mantion that my page is working in a frame, that why it can't get the data from url i want :)
Since you're in a frame, if you need to get the href from the main window, do this:
var href = window.top.location.href;
Then process it.
That code has to run from the page whose URL you're mining for parameter values. In other words, it operates only on the current URL of the page it's on. It works fine.
If you want a function that gives you parameter values given an arbitrary URL, you'd just need to add an additional parameter:
function getUrlParam(param, url) {
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
url = url || decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
alert(getUrlParam("process_number", "http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192"));

Getting Query Parameter from a URL which inturn has some URL with Query parameters

I've the following URL
http://somesite/somepage.aspx
I pass a query parameter value which has another URL with query parameters like this.
http://somesite/somepage.aspx?pageURL=http://someothersite/someotherpage.aspx?param1=value&source=http://anotheronesite/anotherpage
I need to get the pageURL value as the one in the bold letters. But i'm getting
http://someothersite/someotherpage.aspx?param1=value
and i'm not getting the source param. I'm using the following JavaScript function -
function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Any ideas?
You need to use URL encoding to encode the parameter. Otherwise & is treated as reserved character and belongs to the "base URL".
have u considered html url encoding the pageURL parameter?
this would greatly simplify your task

Categories