Reputation: 7469
I'm trying to pass the following string:
NSString* jsString = [NSString stringWithFormat:@"myFunc(\"%@\");", myParameter];
from Objective C to JavaScript using the stringByEvaluatingJavaScriptFromString, where myParameter is a string value. How can I ensure that the myParameter string doesn't contain any JS-unsafe characters without being properly escaped?
E.g. the following string would mess things up:
parameter");alert('scam');
The myParameter string will be the name of a contact from the address book, making it perfectly possible to have the above string entered.
Upvotes: 3
Views: 2566
Reputation: 4916
Depending on your usage requirements, you could use a 'template' approach:
#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];
Upvotes: 0
Reputation: 523304
You can replace every "
with \"
:
NSString* filteredParam = [myParameter stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
NSString* filteredParam = [filteredParam stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
Upvotes: 2