Escaping characters in Objective-C on iPhone

I am trying to pass the following line:

NSString* jsString = [NSString stringWithFormat:@"myFunc(\"%@\");", myParameter];

from Objective-C to JavaScript using stringByEvaluatingJavaScriptFromString, where myParameter is a string value. How can I guarantee that the myParameter string does not contain JS-unsafe characters without proper escaping?

eg. the following line will mess things up:

parameter");alert('scam');

The string myParameter will be the name of the contact from the address book, which makes it possible to include the specified string.

+3
source share
2 answers

You can replace each "with \":

NSString* filteredParam = [myParameter stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
NSString* filteredParam = [filteredParam stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
+2
source

"":

#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];
0

Source: https://habr.com/ru/post/1736282/


All Articles