Should URLs be encoded with encodeURIComponent() or escape()? - javascript

I am trying to encode URL using encodeURIComponent method. Some parameters in URL also contain special characters (of ISO-8859-1 charset) like é, è, which are not correctly encoded.
For example éis encoded to %C3%A9 instead of %E9
As a alternative I have used escape method for encoding and it is working absolutely fine.
But it does not encode some characters like + - * / . _ #
I am in doubt whether i should use it or not and most of the articles say that escape() should be avoided. Can anyone please tell me how can I get the correct encoding using encodeURIComponent or should I use escape?
CODE: there is a function "get" in which request is sent and encodeFormularDatas is used to encode url parameters. HTML page encoding is ISO-8859-1.
this.get = function(url, answerTreatement, options) {
var request = this.newRequest();
var target = url;
if (options.parameters) {
target += "?"+this.encodeFormularDatas(options.parameters);
}
request.open("POST", target, true);
request.send(null);
}
this.encodeFormularDatas = function(values) {
var pairs = [];
var regexp = /%20/g; // encoded space
for (var name in values) {
var value = values[name];
var pair = encodeURIComponent(name).replace(regexp, "+") + '=' +
encodeURIComponent(value).replace(regexp, "+");
pairs.push(pair);
}
return pairs.join('&');
};

Related

Prevent URL.toString() from escaping plus (+) symbols

I want to write a method that takes an array of strings and joins them with a + symbol, similarily to what Google does. This is my method:
function getQueryUrl(array) {
let urlParamsString = array.join("+");
const url = new URL(window.location);
url.searchParams.set("query", urlParamsString);
return url.toString();
}
But instead of getting the cleanly plus-separated URL, the URL API escapes the symbols with %2B. Is there any way to prevent this (apart from straight-up replacing the escaped symbols back to +)?
Try unescape() function:
function getQueryUrl(array) {
let urlParamsString = array.join("+");
const url = new URL(window.location);
url.searchParams.set("query", urlParamsString);
return unescape(url.toString());
}
Update:
use decodeURIComponent(url.toString());

How to send a string as a parameter of an API method through URL which contains '+' in Typescript

I am new to Angular 4. Here I am trying to pass a string to an API call .
Currently I just assigned the sequence of characters to a string variable and passed it to an API URL .
Here the problem is when I receive the string in API it loses the + in the string and each + is replaced by a space .
So how should I pass the string which has the + symbols in it to the API.
app.component.ts
var isValidString = "AhU29yCXdtoaNyQ8rhUBZMz0MieMNBTUaaA04hO+pGzd/iK01sQx6ckMi8LqCdyphShlBt9QhLtCizcUsy708eU90GD7Qg==";
this.CartdataService.validateString(isValidString).subscribe(data => {
console.log(data);
});
Here the string has a + in it ,which is not present when I receive it in my API function.
Angular.Service:
validateString(isValidString){
return this.http.get(this.validate_User_Password_URL = this.SERVER_URL+`/api/ECOMAPI/validateUserPassword/?mValidateString=${validateString}`);
}
In API
public async Task<HttpResponseMessage> validvalidateUserPassword(string myString)
{
if (myString) != " ")
{
.............
}
}
While debugging the myString the string has the space instead of +
Can anyone help me to fix this .
Have you tried url encoding the string and check if it works?
You can use encodeURIComponent() to encode special characters.
var isValidString = "AhU29yCXdtoaNyQ8rhUBZMz0MieMNBTUaaA04hO+pGzd/iK01sQx6ckMi8LqCdyphShlBt9QhLtCizcUsy708eU90GD7Qg==";
var encoded = encodeURIComponent(isValidString);
// then append the encoded one to the url instead of the original string
You can use the encodeURI and decodeURI
var encoded = encodeURI(uri);
Your code
var isValidString = encodeURI("AhU29yCXdtoaNyQ8rhU+pGzd/i......");
// now call the service method with above encoded string
Move to your API Code:
if (!string.IsNullOrEmpty(myString))
{
myString = HttpUtility.UrlDecode(myString);
// Rest of your code
}
I'm quite sure that if you use HttpParams instead of assembling the string by yourself, Angular does the encoding stuff for you. Something like this
let str = "adam+eve"
let params = new HttpParams().set("isValidString", str);
return this.http.get("http://foo.bar", {params}) as Observable<Any>
should result in a call to
http://foo.bar?validString=adam+eve

URL Param: Line break %0A causing JSON.parse to choke

I am parsing a multiline value from a textarea encoded in the URL:
// URL Params:
?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true
// JAVASCRIPT
var _url = window.location.href;
var _queryParams = decodeURIComponent( _url.split('?')[1] );
var _search = _queryParams;//location.search.substring(1);
var _data = JSON.parse('{"' + decodeURI(_search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
But I'm getting an Syntax Error: Unexpected token... error from the JSON.parse() function whenever I have a multiline text value in the d= URL param above:
&d=asdf%0A%0Aasdf
What .replace() regex pattern do I need to do to handle the line break encoding, %0A?
EDIT:
I'm already successfully converting the URL params to a javascript object. The problem is that the replace([pattern match]) functions inside are choking on the mutliline text character: %0A.
Parse the query string using URLSearchParams, and then use URLSearchParams's entries method to turn it into a plain Javascript object, and then stringify it to turn it into a JSON-formatted string:
const queryString = '?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true';
const params = new URLSearchParams(queryString);
console.log(params.get('d'));
const queryObj = {};
for (const [key, val] of params.entries()) {
queryObj[key] = val;
}
console.log(JSON.stringify(queryObj));

Solid javascript encode uri

I've read this and more articles:
When are you supposed to use escape instead of encodeURI / encodeURIComponent?
Still I have not found a solid encode/decode uri solution.
Let's say I have these variables
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
An unencoded url would be:
var url 'http://example.com/?first=' + first + '&second=' + second + '&third=' + third + '&fourth=' + fourth;
Later it should be in an ajax request like:
xhr = new XMLHttpRequest();
xhr.open('POST', url );
I tried this:
var url 'http://example.com/?first=' + encodeURIComponent(first);
But it does not work with #. So what is a solid encoding solution for all characters?
I don't use jQuery, just javascript.
Use the encodeURIComponent when encoding uri parameters. When you encode a hashtag with that function it will result in the string "%23".
So in your example:
var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
var url = 'http://example.com/?first=' + encodeURIComponent(first) + '&second=' + encodeURIComponent(second) + '&third=' + encodeURIComponent(third) + '&fourth=' + encodeURIComponent(fourth);
Will result in the url variable containing the string:
http://example.com/?first=Hello%26and&second=Let's%20have%20cite&third=And%20%22hash%2C.%23%24&fourth=%C3%A5%C3%A4%C3%B6%20other%20strange%20chars
More information of the encodeURIComponent function can be found here.
(citation from w3 school) This function encodes special characters. In
addition, it encodes the following characters: , / ? : # & = + $ #
You can try using escape() function. This has saved me many-a times.
escape('#') does yield %23.

Trouble reading a query string in a Query String?

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.

Categories