Javascript converting ' to URL language - javascript

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 "'".

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;
}

Force percent-encode in JS

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

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);

Unexpected Token Illegal with onclick Java Script in Salesforce.com

I have been working on this most of the morning but to no end. I am trying to execute a button that uses OnClick Java in Salesforce.com and it keeps throwing errors. I think the issue may be with special characters in the data as it works when I simply use just text. But any time numbers or any special characters are present I get the error "unexpected token ILLEGAL". Can anyone help me to see what I am doing wrong and how I can get away from failing when special characters are involved?
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
var opptyObj = new sforce.SObject("Opportunity");
var caseObj = new sforce.SObject("Case");
var today = new Date();
var sOpptyId = "{!Case.Opportunity__c}";
if( sOpptyId != "")
{
alert("This case is already tied to an opportunity!");
}
else
{
opptyObj.AccountId = "{!Case.AccountId}";
opptyObj.CloseDate = sforce.internal.dateTimeToString(today);
opptyObj.Description="{!Case.Description}";
opptyObj.Case__c = "{!Case.Id}";
opptyObj.Name = "{!Case.Subject}";
opptyObj.StageName = "Estimate in Progress";
opptyObj.Created_from_Case__c = "Y";
opptyObj.Type = "New Business";
opptyObj.Amount = ".01";
var opptyresult = sforce.connection.create([opptyObj]);
if (opptyresult[0].success=='false')
{
alert("Opportunity creation failed: " + opptyresult[0].errors.message);
}
else
{
caseObj.Id = '{!Case.Id}';
caseObj.Opportunity__c = opptyresult[0].id;
caseObj.Status = "Estimate in Progress";
var caseResult = sforce.connection.update([caseObj]);
if(caseResult[0].success == 'false')
{
alert("Case update failed: " + caseResult[0].errors.message);
}
else
{
alert("An opportunity has been created and linked to this case.");
location.reload(true);
}
}
}
Assuming this is some kind of template, whatever is rendering this needs to properly escape some values in the strings it's inserting.
Given this:
opptyObj.Description="{!Case.Description}";
Let's say I enter a description consisting of this:
"That is awesome," said John.
When that is rendered in your template the result is this:
opptyObj.Description=""That is awesome," said John.";
As you might be able to see, the result is a syntax error.
You need to escape quote characters in an text inserted this way. And without knowing what is technology rendering this template I can't give you any specifics, but you want to replace " with \" and ' with \'. The \ escapes characters, forcing them to be treated as literal characters in the string instead of other special meaning.
This must be done as it's being inserted into the script. Something in the spirit of this:
opptyObj.Description="{!Case.Description.replace(/'/, "\\'").replace(/"/, '\\"')}
Exactly how to do that depends on what language or template engine is being used here. But th eresult should look like this:
opptyObj.Description="\"That is awesome,\" said John.";
Ruby on Rails implements an escape_javascript method, which sanitizes data for injection into Javascript. It does the following replacements. It seems like a good baseline.
'\\' => '\\\\'
'</' => '<\/'
"\r\n" => '\n'
"\n" => '\n'
"\r" => '\n'
'"' => '\\"'
"'" => "\\'"
UPDATE:
According to this: http://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_scontrols.htm
It looks like you want the JSENCODE function. Something like this, perhaps?
opptyObj.Description="{!JSENCODE(Case.Description)}";

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