简体   繁体   中英

How do you define a string in JavaScript that could contain any character?

Even though I'm using a Salesforce variable in my JavaScript, it is not necessary to know Salesforce to answer my question. There's a password field I want to access. I can do this by using the Salesforce variable, {!Account.Password__c} , inside my JavaScript like so:

var p = '{!Account.Password__c}';

I've been using this for a long time, but there are some instances where it doesn't work. The only problem is that the password could contain any character (as a good password should). So if it contains a single quote, then this JavaScript will not run. I could write it with double quotes:

var p = "{!Account.Password__c}";

But it could contain a double quote also. It could also contain forward slashes and/or back slashes.

The password string needs to be able to take any of these:
Idon'tknow
pass"word"
/-\\_|)_/-\\_/\\/\\
"'!@#
+*co/rn

This is my code:

var u = '{!Account.Email_Address__c}';
var p = escape(encodeURIComponent('{!Account.Password__c}'));
window.open('http://mywebsite.com/?&u=' + u + '&p=' + p,'_blank');

What you're looking for is the JSENCODE function. It will escape quotes, backslashes, and anything else that might mess up your Javascript string.

var p = '{!JSENCODE(Account.Password__c)}';

If your Javascript is inside an HTML tag (eg: in an 'onclick' attribute) then use the JSINHTMLENCODE function, which will html-encode the characters <&> .

These are documented in the Visualforce Functions reference.

Your problem is that of escaping. You can backslash any character in a string - so if you have, say, owowow"'!thisishard as a password, to assign it straight up to a JS var, you would do this:

var p = "owowow\"\'!thisishard";

Which deals with the escaping. You do not need to do this if you have acquired the variable from another source (say, a text element through element.value ).

This does not reove a couple of issues:

  1. Passing passwords through GET params is pretty high up on the OWASP guidelines of things not to do. The reason being that they will show up on server logs in addition to being sniffable through conventional means.
  2. Why on earth are you doing this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM