JScript Escape an ampersand in payload data for URL - jscript

I am attempting to launch a view using the following JS function:
$('#filterTop').click(function () {
var filterValue = $('#filterValueTop').val();
refreshView(`#Url.Action(Model.Action, Model.Controller)?pageSize=#Model.PageSize&pageNumber=#Model.PageNumber&sortDesc=#Model.SortDescending&filterType=#Model.FilterType&filterValue=${filterValue}&showAll=#Model.ShowAll` + `#Model.Payload`, '#Model.ResultView');
});
It worked great until I needed to append a static payload to the end of the URL. The relevant part is line 3 at the end:
&showAll=#Model.ShowAll` + `#Model.Payload`
I am assigning #Model.Payload a value of:
opts.Payload = "&batchID=" + batchID;
or "&batchID=25". The resulting URL is:
https://localhost:44303/Employee/Repaginate?pageSize=20&pageNumber=1&sortDesc=True&filterType=Name&filterValue=Jes&showAll=False&batchID=25
For some reason, it's translating the "&" to "&a.m.p;" (with no periods) which isn't a valid URL. I've tried various methods of escaping the character like using "%26", "/&", and several other garden varieties but alas, my attempts have been in vain. Any suggestions on what I am doing wrong?

Related

How to avoid google translate to translate :parameters

I'm using a library nikaia/translation-sheet who basically pulls all the translations from the Laravel site into a google spreadsheet making it "easily" translatable with =GOOGLETRANSLATE(A1)
The problem comes with the parameters:
:price
:amount
:etc
So I've got the idea to substitute ":" with #nonmakingsenseworblablaprice so Google couldn't translate example:
=SUBSTITUTE(GOOGLETRANSLATE(SUBSTITUTE(B2;":";"#nonmakingsenseworblabla");"ES";"EU");"#nonmakingsenseworblabla";":")
Well, not sure why Google eats some letters and puts new ones:
:amount de saldo -> #nonmakingseseworblatamount of saldo
So I decided to do something like detect the parameter and change :amount to :a_m_o_u_n_t and that is apparently working and not being weirdly parsed converted or translated.
I was looking for a solution and found a similar idea but having problems migrating it to spreadsheets script plus is not detecting the parameter
Any one knows how to detect all :parameters in a sentence and put a symbol, slash, dash etc between the characters or letters? Example:
The amount :amount for this order number :order_id is :price
I've also tried regex but not been lucky so far
=REGEXREPLACE(GOOGLETRANSLATE(REGEXREPLACE(B22; ":(\w)([\w]+)"; "{%$1_$2%}"); "ES"; $C$1); "{%(\w)_([^_]+)%}"; ":$1$2")
There's a regex to select the spaces between letters, but good luck making that in excel or spreadsheets. Demo
Finally I've created a script to avoid parameters translation:
function translate(cell, lang) {
const content = cell.toString();
const keys = [];
const enc = content.replace(/:([\w_]+)/ig, function(m, param) {
const n = `[§${keys.length}]`;
keys.push(param);
return n;
});
return LanguageApp.translate(enc, "es", lang).replace(/\[§(\d+)\]/ig, function(m, param) {
return `:${keys[param]}`;
});

Why postgres is returning additional backslash in a simple query

So in my node code postgres query is returning double quotes when it's returning its values.
As opposed to the query at pgAdmin.
I already tried to solve it using regex but this attempt was innefective. So if anyone had a problem like this and could help me, I would be glad.
Thanks in advance
There are neither quotes nor extra back slashes in the string. They are part of the string representation as literal.
Try console.log(value) - or even directly console.log('/\\w/g') - and you'll see the output is /\w/g as expected.
To answer my own question, after a lot of reading and researching, I managed to discover that because a backslash character is a special character it will create some problems around its implementation in regex, because it is not permitted to have a lone backslash stored in a variable for example.
This would never work stored inside a variable because the backslash have to be escaped.
/\w+/ig
Javascript will transform it automatically to be able to perform.
/\w+/ig
When reading
RegExp - Javascript documentation, I came across an interesting statement, the RegExp function will recognize and use a double slash regex, thankfully!
So I just adapted my regex to split it's statement from it's flags and mount it again using RegExp.
Below is the code that I used to solve this problem
// Getting values from postgres
const values = (await pgConn.admRead.query(clientQuery)).rows[0].value || [];
// Splitting regex ( values: /\w/g )
const valuesSplit = values.split('/'); // RESULT -> ['', w, g]
// Removing first array item when it's empty
if (valuesSplit[0].length === 0) {
valuesSplit.shift();
}
// Creating regex from splitted array
const regexOperation = new RegExp(valuesSplit[0], valuesSplit[1]);
// Executing replace function
const messageMasked = message.replace(regexOperation, '*');
return messageMasked;

golang remove characters (used for readability) in const string at compile time (spaces, \n and \t)

Spaces are useful to indent urls, sql queries to make it more readable.
Is there a way to remove characters from a const string at compile time in golang ?
ex: (runtime version)
const url = `https://example.com/path?
attr1=test
&attr2=test
`
// this is the code to be replaced
urlTrim := strings.Replace(
strings.Replace(url, "\n", "", -1)
)
Constant expressions cannot contain function calls (except a few built-in functions). So what you want cannot be done using a raw string literal.
If your goal with using multiple lines is just for readability, simply use multiple literals and concatenate them:
const url = "https://example.com/path?" +
"attr1=test" +
"&attr2=test"
Try it on the Go Playground.
See related question: Initialize const variable

Read parameter from URL - plus character converted to space [duplicate]

Say I have a URL
http://example.com/query?q=
and I have a query entered by the user such as:
random word £500 bank $
I want the result to be a properly encoded URL:
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.
URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.
String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString() as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8".
Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).
Also note that there are three encode() methods. One without Charset as second argument and another with String as second argument which throws a checked exception. The one without Charset argument is deprecated. Never use it and always specify the Charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.
All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
See also:
What every web developer must know about URL encoding
I would not use URLEncoder. Besides being incorrectly named (URLEncoder has nothing to do with URLs), inefficient (it uses a StringBuffer instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.
Instead I would use URIBuilder or Spring's org.springframework.web.util.UriUtils.encodeQuery or Commons Apache HttpClient.
The reason being you have to escape the query parameters name (ie BalusC's answer q) differently than the parameter value.
The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.
Sample code:
import org.apache.http.client.utils.URIBuilder;
URIBuilder ub = new URIBuilder("http://example.com/query");
ub.addParameter("q", "random word £500 bank \$");
String url = ub.toString();
// Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24
You need to first create a URI like:
String urlStr = "http://www.example.com/CEREC® Materials & Accessories/IPS Empress® CAD.pdf"
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
Then convert that URI to an ASCII string:
urlStr = uri.toASCIIString();
Now your URL string is completely encoded. First we did simple URL encoding and then we converted it to an ASCII string to make sure no character outside US-ASCII remained in the string. This is exactly how browsers do it.
Guava 15 has now added a set of straightforward URL escapers.
The code
URL url = new URL("http://example.com/query?q=random word £500 bank $");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String correctEncodedURL = uri.toASCIIString();
System.out.println(correctEncodedURL);
Prints
http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$
What is happening here?
1. Split URL into structural parts. Use java.net.URL for it.
2. Encode each structural part properly!
3. Use IDN.toASCII(putDomainNameHere) to Punycode encode the hostname!
4. Use java.net.URI.toASCIIString() to percent-encode, NFC encoded Unicode - (better would be NFKC!). For more information, see: How to encode properly this URL
In some cases it is advisable to check if the URL is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.
Here are some examples that will also work properly
{
"in" : "http://نامه‌ای.com/",
"out" : "http://xn--mgba3gch31f.com/"
},{
"in" : "http://www.example.com/‥/foo",
"out" : "http://www.example.com/%E2%80%A5/foo"
},{
"in" : "http://search.barnesandnoble.com/booksearch/first book.pdf",
"out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
}, {
"in" : "http://example.com/query?q=random word £500 bank $",
"out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
}
The solution passes around 100 of the test cases provided by Web Platform Tests.
Using Spring's UriComponentsBuilder:
UriComponentsBuilder
.fromUriString(url)
.build()
.encode()
.toUri()
The Apache HttpComponents library provides a neat option for building and encoding query parameters.
With HttpComponents 4.x use:
URLEncodedUtils
For HttpClient 3.x use:
EncodingUtil
Here's a method you can use in your code to convert a URL string and map of parameters to a valid encoded URL string containing the query parameters.
String addQueryStringToUrlString(String url, final Map<Object, Object> parameters) throws UnsupportedEncodingException {
if (parameters == null) {
return url;
}
for (Map.Entry<Object, Object> parameter : parameters.entrySet()) {
final String encodedKey = URLEncoder.encode(parameter.getKey().toString(), "UTF-8");
final String encodedValue = URLEncoder.encode(parameter.getValue().toString(), "UTF-8");
if (!url.contains("?")) {
url += "?" + encodedKey + "=" + encodedValue;
} else {
url += "&" + encodedKey + "=" + encodedValue;
}
}
return url;
}
In Android, I would use this code:
Uri myUI = Uri.parse("http://example.com/query").buildUpon().appendQueryParameter("q", "random word A3500 bank 24").build();
Where Uri is a android.net.Uri
In my case I just needed to pass the whole URL and encode only the value of each parameters.
I didn't find common code to do that, so (!!) so I created this small method to do the job:
public static String encodeUrl(String url) throws Exception {
if (url == null || !url.contains("?")) {
return url;
}
List<String> list = new ArrayList<>();
String rootUrl = url.split("\\?")[0] + "?";
String paramsUrl = url.replace(rootUrl, "");
List<String> paramsUrlList = Arrays.asList(paramsUrl.split("&"));
for (String param : paramsUrlList) {
if (param.contains("=")) {
String key = param.split("=")[0];
String value = param.replace(key + "=", "");
list.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
else {
list.add(param);
}
}
return rootUrl + StringUtils.join(list, "&");
}
public static String decodeUrl(String url) throws Exception {
return URLDecoder.decode(url, "UTF-8");
}
It uses Apache Commons' org.apache.commons.lang3.StringUtils.
Use this:
URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());
or this:
URLEncoder.encode(query, "UTF-8");
You can use the following code.
String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8"); // No change
String encodedUrl2 = URLEncoder.encode(query, "UTF-8"); // Changed
String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); // Changed
System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);

Dynamic Strings, AS2, needed on one line

Ok, so I'm creating a Flash HUD in AS2 that runs on the Surface and connects to our server.
As it stands now, I'm having to hard code the IP addresses for the Surface to connect to, and I'm trying to get past this.
I have 4 text fields for the user to enter the 4 fields of IP address data. My issue at the moment is that if I set the String variable literally, it works fine. But if I dynamically create the string, instead of outputting on one line, it outputs each of the 4 strings separately.
Here's my code:
var newIP1 = getIP.IPtext.IP1.text; //grabbing the data from the UI
var newIP2 = getIP.IPtext.IP2.text;
var newIP3 = getIP.IPtext.IP3.text;
var newIP4 = getIP.IPtext.IP4.text;
var ipArray = new Array(newIP1,newIP2,newIP3,newIP4); //setting the array
trace (ipArray.join(".")); // output the string, replacing the commas with a period
//output:
//10
//.255
//.255
//.22
//If I do this it works fine
var IPstr = "10.255.255.2";
trace(IPstr);
// output: 10.255.255.22
I appreciate any help on this, thanks in advance.
Your code looks good and should work as expected.
One thing to check would be to see if there isn't a carriage return or newline character being added to each individual input box. One way to check would be to check the length of each of your input strings to ensure there isn't an invisible character there.

Resources