I have a HTML page which is loaded using a URL that looks a little like this:
http://localhost:8080/GisProject/MainService?s=C&o=1
I would like to obtain the query string parameters in the URL without using a jsp.
Questions
Can this be done using Javascript or jQuery?
Because I want to test my page using my Node.js local server before deploying it in the remote machine which uses a Java server.
Is there any library that will allow me to do that?
A nice solution is given here:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample:
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');`
Chrome 49 implements URLSearchParams from the URL spec, an API which is useful for fiddling around with URL query parameters. The URLSearchParams interface defines utility methods to work with the query string of a URL.
So what can you do with it? Given a URL string, you can easily extract parameter values as in the code below for s & o parameter:
//http://localhost:8080/GisProject/MainService?s=C&o=1
const params = new URLSearchParams(document.location.search);
const s = params.get("s");
const o = params.get("o");
console.info(s); //show C
console.info(o); //show 1
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
We can then parse the query string’s parameters using URLSearchParams:
const urlParams = new URLSearchParams(queryString);
Then we call any of its methods on the result.
For example, URLSearchParams.get() will return the first value associated with the given search parameter:
const product = urlParams.get('product')
console.log(product);
// shirt
const color = urlParams.get('color')
console.log(color);
// blue
const newUser = urlParams.get('newuser')
console log(newUser);
// empty string
Other Useful Methods
Let's get a non-encoded URL for example:
https://stackoverflow.com/users/3233722/pyk?myfirstname=sergio&mylastname=pyk
Packing the job in a single JS line...
urlp=[];s=location.toString().split('?');s=s[1].split('&');for(i=0;i<s.length;i++){u=s[i].split('=');urlp[u[0]]=u[1];}
And just use it anywhere in your page :-)
alert(urlp['mylastname']) //pyk
Even works on old browsers like ie6
Related
I have a CSR and I can parse all the data with pkijs.org lib, but I have no luck to parse alternative names data. How is it possible to do with a javascript? Some other libs can be in use, I guess, do you know one?
Following the docs of CertificationRequest class provided by pkijs here https://pkijs.org/docs/classes/CertificationRequest.html. We can see that the structure of a CSR. The subject alternative name will be stored in attributes propery of CertificationRequest object. But the structure inside of attributes is quite complex to make it as plain text. This is my code used to print out the subject alternative name
const pkijs = require('pkijs');
const utils = require("pvtsutils");
const asn1js = require("asn1js");
let base64 = "<your_csr_in_base64>"
let csrraw = utils.Convert.FromBase64(base64);
console.log(csrraw)
const pkcs10 = pkijs.CertificationRequest.fromBER(csrraw);
let seq = pkcs10.attributes[0].values[0];
let exts = pkijs.Extensions.fromBER(seq.toBER(false));
console.log(exts);
var san = getExtentionsForSANFromExtensions(exts);
console.log(san)
if (san != undefined) {
san.names.forEach(element => {
console.log(element.type + " = " + element.value)
});
}
function getExtentionsForSANFromExtensions(exts){
for (var i = 0 ; i< exts.extensions.length; i++) {
var ext = exts.extensions[i];
if(ext.extnID == '2.5.29.17') {
var octetString = asn1js.fromBER(ext.extnValue.toBER(false)).result;
return pkijs.GeneralNames.fromBER(octetString.getValue());
}
}
}
I've tested this code and it works properly with CSR generated by Keystore Explorer. Have not tested with another tool to generate CSR that supports subject alternative names.
Cheers!
If you have a CSR and need to extract the alternative names data from it, you can use the following command:
openssl req -in csr.pem -noout -text
This will print out the entire CSR, including the alternative names data.
I am writing a function that detects if the current URL contains a certain substring. If it contains, then I would like to remove it.
For example,
localhost/4000?ab=2&item=google
localhost/4000?ab=2&item=google123
localhost/4000?ab=2&item=google1233&haha=helpful
My idea is below....but kinda stuck in the process
function changeUrl(item) {
var currentUrl = window.location.href;
if(currentUrl.includes('&item=') ){
.....
.....
return currentUrl
}else return;
}
I wouldn't try to manipulate it as a string. JavaSccript has a perfectly good tool to manipulate URLs, and you might as well use it:
str = 'http://localhost/4000?ab=2&item=google1233&haha=helpful';
url = new URL(str);
url.searchParams.delete('item'); // Idempotent call
result = url.toString();
In this case, it's better to use URLSearchParams.
MDN DOCS
The URLSearchParams interface defines utility methods to work with the query string of a URL.
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
// you can see params by this way
for (let p of params) {
console.log(p);
}
// if you want to check if some params are exist
console.log(params.has('foo')); // true
// if you want to delete some params
console.log(params.toString());
params.delete('foo');
console.log(params.toString());
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
I have been struggling with dynamically changing HTML content using URL variables. Let me give you an example and than provide you my code thus far.
Ex. I have a landing page with content to be changed. I would like to have a variable in my URL www.domain.com/header=new-content
I would like to be able to rewrite the HTML to show the new header using Javascript or Jquery. Here is what I have thus far. Seems like I am missing the trigger or if/else statement.
Thank you so much!
<script>
var element = document.getElementById("header");
element.innerHTML = "New Content";
</script>
First of all, when you're dealing with URL parameters, you should place a ? before you start defining parameters. This will result in the browser retrieving the page www.foo.bar/ instead of www.foo.bar/header=new-content. Once you add the question mark, you can retrieve URL parameters using the following snippet. I retrieved this from this question.
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
In your specific case, your final code, after defining the above function, might look something like this:
<script>
var header = getUrlParameter('header');
document.getElementById('header').innerHTML = header;
</script>
This will retrieve the URL parameter header and change the value of the element with ID header to the value contained in the URL. For the URL www.foo.bar/?header=new-content, the element's value would be changed to new-content. If you want to have spaces in the variable, you can remove the URL-encoded characters (ex. %20 for space) by changing the first line in the above snippet to this:
var header = decodeURIComponent(getUrlParameter('header'));
Last minute addition: I just noticed that another answer with more-or-less the same code snippet came in while I was writing this. Whoops. :)
You could read the url and extract the desired paramenter with a function such as:
function fGetUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
};
So if you are accessing a url such as:
http://www.domain.com/?header=new-content
You could store the parameter in a variable
var stringHeader = fGetUrlParameter("header")
and modify your element html
var element = document.getElementById("header");
element.innerHTML = stringHeader;
I'm not sure I understood your question.
Assuming that you want to pass a parameter using the URL the correct way to rewrite your url would be
www.domain.com?header=new-content
That would make your variable named header equal the value of new-content.
The way to extract your data would be:
<script>
var element = document.getElementById("header");
//use your variable
</script>
Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.