[英]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. 即使我在JavaScript中使用Salesforce变量,也不必知道Salesforce即可回答我的问题。 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: 我可以通过在JavaScript中使用Salesforce变量
{!Account.Password__c}
来做到这一点,如下所示:
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.
因此,如果其中包含单引号,则此JavaScript将无法运行。 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. 您正在寻找的是JSENCODE函数。 It will escape quotes, backslashes, and anything else that might mess up your Javascript string.
它将转义引号,反斜杠以及其他可能弄乱Javascript字符串的东西。
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 <&>
. 如果您的Javascript在HTML标记内(例如,在'onclick'属性中),则使用JSINHTMLENCODE函数,它将对字符
<&>
进行html编码。
These are documented in the Visualforce Functions reference. 这些内容记录在Visualforce函数参考中。
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: 您可以反斜杠字符串中的任何字符-因此,如果您拥有
owowow"'!thisishard
作为密码,可以直接将其分配给JS var,则可以这样做:
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
). 你不需要做这个,如果你已经获得来自其他来源的变量(比如,通过文本元素
element.value
)。
This does not reove a couple of issues: 这不会解决几个问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.