I have a string of ASCII characters (created randomly by [NSString stringWithFormat:@"%c", someNumber]), and I want to use that string as input for a javascript method. Something like:
[webView_ stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"my_javascript_method(\"%@\")", myASCIIString]];
How can I escape the NSString? I tried to look into encodeURI and decodeURI, but haven't found any solution yet.
NSJSONSerialization
is right there in the corner. To escape NSString to Javascript string literal is hard and could be done wrong easily. (JSONKit
use lines of code to deal with it https://github.com/johnezang/JSONKit/blob/82157634ca0ca5b6a4a67a194dd11f15d9b72835/JSONKit.m#L1423)
Below is a little category method to escape the NSString
object.
#import "NSString+JavascriptEscape.h"
@implementation NSString (JavascriptEscape)
- (NSString *)stringEscapedForJavasacript {
// valid JSON object need to be an array or dictionary
NSArray* arrayForEncoding = @[self];
NSString* jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:arrayForEncoding options:0 error:nil] encoding:NSUTF8StringEncoding];
NSString* escapedString = [jsonString substringWithRange:NSMakeRange(2, jsonString.length - 4)];
return escapedString;
}
@end
Also, one thing to notice, you've gotta use double quotes in the argument to the javascript function. E.g.,
NSString *javascriptCall =
[NSString stringWithFormat:@"MyJavascriptFunction(\"%@\")", escapedString];
[self.webView stringByEvaluatingJavaScriptFromString:javascriptCall];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With