Encoding URL in JavaScript - javascript

I'm unable to encoding data URI:
var uri ="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQo...";
var res = encodeURI(uri);
document.location.href = 'display.jsp?img='+res;
After encoding, I'm getting the same uri. display.jsp is landing as am empty page.

There is no encoding happening because what you have there is already a valid, completely encoded URI.
If you want to use that as a parameter in an other URI, you should use encodeURIComponent:
document.location.href = 'display.jsp?img='+encodeURIComponent(uri);

It is not correct to use encodeURI() as this function encodes special character except: , / ? : # & = + $ #
Use encodeURIComponent() to encode these characters.
For more info check below link:
http://www.w3schools.com/jsref/jsref_encodeuri.asp

Your problem is that the encodeURI function is for making a URL valid for a browser, not for formatting content into a URL (which is what you're doing). A base64 string is already formatted in such a way that it registers as valid. To encode it as part of the URL, you need to use encodeURLComponent.
Basically, just use:
var uri ="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQo...";
var res = encodeURIComponent(uri);
document.location.href = 'display.jsp?img='+res;
For more info, check out: When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Related

How to escape slash in URL parameter

$.ajax({
url: "/api/v1/cases/annotations/" + case_id + "/" + encodeURIComponent(current_plink),
I am using encodeURIComponent to escape slash. But it does not work for me. This code convert "slash" to "%2F" but apache does not recognize it.
My php part like this :
$app->get('/cases/annotations/:case_id/:prep_name', 'authenticatePathologist', function($case_id, $prep_name) use ($app) {
If i try to send parameter which include slash, it returns page not found.
But if i try to send parameter which does not include slash, it returns OK.
You should encode it twice with encodeURIComponent, i.e. encodeURIComponent(encodeURIComponent(current_plink)). If you encode it only once, the server decodes it, and it's the same as not encoding it at all.
you should follow
AllowEncodedSlashes Directive
I too had a similar issue with url like:
?filters=new:item:text
where it required to escape the colons. for that I tried replacing it to format
?filters/:items/:text but that couldn't work as the Chrome was NOT encoding the '/' value.
Tried the js [escape() method][1] and it worked like charm.
let url = 'https://dev.test.something?filters=';
let filterString = 'new:item:text';
url = url + escape(filterString);
Output:
https://dev.test.something?filters=new%3Aitem%3Atext
Hope this finds helpful!!

javascript how to encode url,which has '-'

I'm trying to pass parameter to a URL like this:
bike-my-myRecharge-dailyAccount-detail.html?billTime=2016-02
but the URL I get is always:
bike-my-myRecharge-dailyAccount-detail.html?billTime=2013
I've tried encodeURIComponent() and encodeURI(), but it doesn't work.
I've tried encodeURIComponent() and encodeURI(), but it doesn't work.
Can you please post the error that you are seeing.
//test url
var uri = "my test.com?bike-my-myRecharge-dailyAccount-detail.html?billTime=2016-02";
var res = encodeURI(uri);
- will be encoded to %2D
You can directly test your encoded url in W3C

encodeURI doesn't escape `equals` - why?

I have an URI like that:
http://client.dev/dap/module/hdfs-web/api/v1.0/clusters/Cluster%201%20-%20CDH4?operation=copy&to=/user/hdfs/year=2016/partial.txt&overwrite=true
I use encodeURI function to escape string. I'm wondering why spaces are encoded with %20 while equals characters are not?
encodeURI encodes a full URI, and URIs can contain = characters. For instance, if a user types in a URI, a first step to resolve it would be to call encodeURI on it.
If on the other hand you are the one constructing the URI, and the input just determines one field (for instance a search query, when given E=mc² you want to resolve https://www.google.com/search?q=E%3Dmc%C2%B2), then you are not encoding a full URI, but a URI component. Use encodeURIComponent for that:
> encodeURIComponent('= ')
'%3D%20'
The encodeURI() function is used to encode a URI.
This function encodes special characters, except:, / ? : # & = + $ # (Use encodeURIComponent() to encode these characters).
Tip: Use the decodeURI() function to decode an encoded URI.
SOURCE: W3Schools

inconsistent window.history.pushState uri encoding

Take url address www.somesite.com/#user1
If I click on a good old fashioned <a href... hyperlink containing the link then the # is percent encoded to %40 in the address bar.
If I use html5's window.history.pushstate("object or string", "Title", 'www.somesite.com/#user1') the # is not endocded - it instead shows as a '#' character.
This inconsistency troubles me. Mayhaps there is a way to make the behaviour consistent?
I have considered encodeURIComponent('www.somesite.com/#user1') for the pushstate url, but this also encodes the '/', and what I am hoping is for the <a href... hyperlink not encode the '#' symbol.
Using encodeURIComponent makes javascript assume there are no special HTTP characters to ignore.
extract the compnenet first:
var url = "www.somesite.com/#user1";
var atPos = url.indexOf('#');
var urlComp= url.slice(atPos); //#user1
url = url.slice(0, atPos);
url += encodeURIComponent(urlComp); //"www.somesite.com/%40user1"

How to prepare encoded POST data on javascript?

I need to send data by POST method.
For example, I have the string "bla&bla&bla". I tried using encodeURI and got "bla&bla&bla" as the result. I need to replace "&" with something correct for this example.
What kind of method should I call to prepare correct POST data?
UPDATED:
I need to convert only charachters which may broke POST request. Only them.
>>> encodeURI("bla&bla&bla")
"bla&bla&bla"
>>> encodeURIComponent("bla&bla&bla")
"bla%26bla%26bla"
You can also use escape() function.The escape() function encodes a string.
This function makes a string portable, so it can be transmitted across any network to any computer that supports ASCII characters.This function encodes special characters, with the exception of: * # - _ + . /
var queryStr = "bla&bla&bla";
alert(queryStr); //bla&bla&bla
alert(escape(queryStr)); //bla%26bla%26bla
Use unescape() to decode a string.
var newQueryStr=escape(queryStr);
alert(unescape(newQueryStr)); //bla&bla&bla
Note:
escape() will not encode: #*/+
encodeURI() will not encode: ~!##$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
After some search on internet, I got the following:
escape()
Don't use it.
encodeURI()
Use encodeURI when you want a working URL. Make this call:
encodeURI("http://www.google.com/a file with spaces.html")
to get:
http://www.google.com/a%20file%20with%20spaces.html
Don't call encodeURIComponent since it would destroy the URL and return
http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html
encodeURIComponent()
Use encodeURIComponent when you want to encode a URL parameter.
param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")
Then you may create the URL you need:
url = "http://domain.com/?param1=" + param1 + "&param2=99";
And you will get this complete URL:
http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99
Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).
REF:When are you supposed to use escape instead of encodeURI / encodeURIComponent?
Also, as you are using JQuery, take a look at this built-in function.
Use encodeURIComponent() as encodeURI() will not encode: ~!##$&*()=:/,;?+'
This has been explained quite well at the following link:
http://xkr.us/articles/javascript/encode-compare/
More recent DOM APIs for URLSearchParams (and via URL, possibly others too) handle encoding in some cases. For example, create or use an existing URL object (like from an anchor tag) I map entries of an object as key value pairs for URL encoded params (to use for GET/POST/etc in application/x-www-form-urlencoded mimetype). Note how the emoji, ampersand and double quotes are encoded without any special handling (copied from the Chrome devtools console):
var url = new URL(location.pathname, location.origin);
Object.entries({a:1,b:"🍻",c:'"stuff&things"'}).forEach(url.searchParams.set, url.searchParams);
url.search;
"?a=1&b=%F0%9F%8D%BB&c=%22stuff%26things%22"
fetch(url.pathname, {
method: 'POST',
headers: new Headers({
"Content-type": "application/x-www-form-urlencoded"
}),
// same format as GET url search params a&b&c
body: url.searchParams
}).then((res)=>{ console.log(res); return res }).catch((res)=>{ console.warn(res); return res; });
I want POST the javascript-created hidden form.
So the question is if encodeURIComponent() should be used on each POST variable.
I haven't found the answer for Dmitry's (and my) question in this thread.
But I have found the answer in this thread.
In case of form/POST where you have upload field(s) you must use <form enctype="multipart/form-data">, if no upload field is used, you should choose yourself as described here.
Submitting the form should do the job completly, so there is no need to use encodeURIComponent() explicitly.
If you create a Http POST without using a form or without some library which creates a Http POST from your data, then you need choose an enctype= and join data yourselves.
This will be easy for application/x-www-form-urlencoded, where you will use encodeURIComponent() on each value and join them exactly as for GET request.
If you decide use multipart/form-data then ....? You should google more how to encode and join them in such case.

Categories

Resources