Javascript iPhone上目标C中的转义字符
我正在尝试传递以下字符串:Javascript iPhone上目标C中的转义字符,javascript,iphone,objective-c,nsstring,escaping,Javascript,Iphone,Objective C,Nsstring,Escaping,我正在尝试传递以下字符串: NSString* jsString = [NSString stringWithFormat:@"myFunc(\"%@\");", myParameter]; 使用stringByEvaluatingJavaScriptFromString从Objective C到JavaScript,其中myParameter是字符串值。如何确保myParameter字符串在未正确转义的情况下不包含任何JS不安全字符 下面的字符串会把事情搞砸: parameter");ale
NSString* jsString = [NSString stringWithFormat:@"myFunc(\"%@\");", myParameter];
使用stringByEvaluatingJavaScriptFromString从Objective C到JavaScript,其中myParameter是字符串值。如何确保myParameter字符串在未正确转义的情况下不包含任何JS不安全字符
下面的字符串会把事情搞砸:
parameter");alert('scam');
myParameter字符串将是通讯簿中联系人的姓名,因此完全可以输入上述字符串。您可以将每个
“
替换为\”
:
根据您的使用要求,您可以使用“模板”方法:
#define JSTemplateCodeKey @"##JS_CODE_HERE##"
// define template (or read it from file, ect...)
NSString *jsTemplate = @"myFunc(\"" JSTemplateCodeKey "\");";
// replace the placeholder in your template with your param
NSString *jsString = [jsTemplate stringByReplacingOccurrencesOfString:JSTemplateCodeKey withString:myParameter];
KennyTM,您提供的代码所做的是用
“\\\\”
替换每个“\\\\”
,而不是用“
替换每个”。
#define JSTemplateCodeKey @"##JS_CODE_HERE##"
// define template (or read it from file, ect...)
NSString *jsTemplate = @"myFunc(\"" JSTemplateCodeKey "\");";
// replace the placeholder in your template with your param
NSString *jsString = [jsTemplate stringByReplacingOccurrencesOfString:JSTemplateCodeKey withString:myParameter];