Force percent-encode in JS - javascript

How can I percent-encode a string like "ü" such that it comes out as "%C3%BC"?
Here's my current implementation:
function percentEncode(ch) {
return '%' + ch.codePointAt(0).toString(16).toUpperCase().padStart(2,'0');
}
But that encodes it as '%FC'.
encodeURIComponent handles it correctly, but I need to encode some characters which encodeURIComponent refuses to encode, so I can't use that.

I think I figured it out.
const UTF8_ENCODER = new TextEncoder();
function percentEncode(str) {
return Array.from(UTF8_ENCODER.encode(str)).map(i => '%' + i.toString(16).toUpperCase().padStart(2,'0')).join('');
}
console.log(percentEncode('ü'))
credit

Related

Filtering with LIKE operator with case-sensitivity

I am trying to do an API call using the LIKE operator however its not returning data case sensitive. How would I go about doing this. So far I have:
queryEvent.query = queryEvent.combo.displayField + " like " + "'%" + query + "%'";
And the filter it generates: filter=name%20like%20%27%25Test%25%27
The content that is generated is using URL Encoding. You need to decode this to get the actual value. Use any standard URL decoder library to do the same.
Or use the following program
public String decodeURL (String url){
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
return result;
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
return url;
}

Advanced Find and Replace Based off What is Found - Javascript

I am trying to simplify a process with a script. What is happening is I have a decent size script that has lots of base-64 encoded strings, and I would like to replace them with the decoded version (using atob and btoa). For example, I have atob("MHhfZXhwb3J0") and would like to replace it with the output of atob("MHhfZXhwb3J0"), which is "0x_export". I have tried splitting the code for atob(", then saving the contents and replacing them, but for some reason it breaks at some point. I have tried using string.replace(/*/g, *), but it seems that you cannot use functions in replace. I am sorry if I am not the best at describing my question, so if anyone has further question, I would be glad to reply.
A small example of what I am trying to do is shown below:
The beginning example script:
function test(callback, number, reason) {
if (number != atob("MA==")) {
console.log(atob("RmFpbGVkOiA=") + reason + atob("LiBQbGVhc2UgdHJ5IGFnYWluLg=="));
} else {
callback(number);
}
}
The afterwards example script:
function test(number, reason) {
if (number != "0") {
console.log("Failed: " + reason + ". Please try again.");
} else {
callback(number);
}
}
You can pass functions to replace - you can paste the whole code into some Javascript editor as a string, and then replace every instance of atob("...") with the decoded text:
const inputScript = `
function test(callback, number, reason) {
if (number != atob("MA==")) {
console.log(atob("RmFpbGVkOiA=") + reason + atob("LiBQbGVhc2UgdHJ5IGFnYWluLg=="));
} else {
callback(number);
}
}
`;
const outputScript = inputScript
.replace(/atob\("([^\"]+)"\)/g, (_, p1) => `"${atob(p1)}"`)
.trim();
console.log(outputScript);

Encoding string is differing with asp.net server.URL encoding when using '?' in the string

When I am using in aps.net to encode the string, the function I'm using is Server.UrlEncode(GAE?), which returns the string GAE%3f.
When I am using javascript function to encode encodeURIComponent(GAE?) it is returning GAE%3F.
But when i validate the string it will never match since my validation failing.
Requirement is there any way to encoded encodeURIComponent(GAE?) as GAE%3f as it is my requirement.
Other wise please let me know Server.UrlEncode code encoding it as capital 'F' this letter making difference.
Note:Any way to get 'F' in small case when I use encodeURIComponent(GAE?), The question mark (?) encoded as %3F but it should be %3f
I think the best approach would be to decode then do the comparison.
But if you have to do the comparison before that for any reason, this is the code you can use to change the encoded "special characters" to lower/upper:
string FixEncode(string val) {
var result = new StringBuilder(val);
int searchIndex = val.IndexOf('%');
while (searchIndex >= 0)
{
result[searchIndex + 1] = char.ToUpper(result[searchIndex + 1]);
result[searchIndex + 2] = char.ToUpper(result[searchIndex + 2]);
searchIndex = val.IndexOf('%', searchIndex + 2);
}
return result.ToString();
}
You can run this function on both strings and then compare:
if (FixEncode(str1) == FixEncode(str2)) { /*...*/ }
Please try Uri.EscapeDataString("?")

Javascript converting ' to URL language

I have a very simple JavaScript function that works totally fine, until one of the variables has a ' in it. This is what I tried:
function search(champ1,champ2,role) {
if((champ1!='')&&(champ2!='')){
if((champ1!=champ2)) {
var champ1_name = encodeURI(champ1);
var champ2_name = encodeURI(champ2);
var role_name = encodeURI(role);
window.location.href="http://myurl.com/"+role_name+"/"+champ1_name+"&"+champ2_name;
return false;
} else if(champ1==champ2) {
window.location.href="http://myurl.com/"+role;
}
}
}
but unfortunately when I run this script the URL still has the ' in it even after they ran through encodeURI()
If you need to escape ', do something like .replace("'", "%27"). Or use a URL escaping function that lets you provide a string of characters that need to be escaped.
decodeURIComponent("%27") converts back to "'".

How to detect whether a string is in URL format using javascript?

I think the question title seems to explain eveything.
I want to detect whether a string is in URL format or not using javascript.
Any help appreciated.
Try this-
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
usage: if (isUrl("http://www.page.com")) alert("is correct") else
alert("not correct");
function IsURL(url) {
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+#)?" //ftp的user#
+ "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:#&=+$,%#-]+)+/?)$";
var re=new RegExp(strRegex);
return re.test(url);
}
Debuggex Demo (Improved version which matches also 'localhost')
try something like this:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
One for the future using the URL constructor and a basic try catch statement, it is supported in most modern browsers. Obviously no IE support...
const isUrl = (str) => {
try {
new URL(str);
return true;
} catch () {
return false;
}
}
If the URL is valid it will get parsed by the constructor and return true.
If the string is not a valid URL the constructor will chuck a syntax error that will get caught and return false.
Try this code. This expression is more complete and takes into account IP address:
function checkUrl(s) {
var regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$/
return regexp.test(s); }
You can use a regular expression for checking the string
^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\#&=+\$,%#]+$
Regular Expressions and Javascript
Had the same task, but all of regex that I found online to check validity of a URL were failed in some test cases.
Here is the regex that worked everything:
/^(http:\/\/www\.|https:\/\/www\.|www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?/
However, If the URL was like: google.com It accepted it as valid (which in my specific case, was considered as invalid)
It worked the best I had found. Worked like a charm!
When given the option, I prefer the simplest solution.
Use _.startsWith(string, 'http') if:
You don't mind if URL is invalid
You're sure the URL being checked will always start with 'http'
You don't expect the string to be another value that might start also with 'http'

Categories

Resources