views:

258

answers:

2

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.

A: 

You can replace every " with \":

NSString* filteredParam = [myParameter stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
NSString* filteredParam = [filteredParam stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
KennyTM
A: 

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];
Brian Chapados