Convert certain characters to escaped unicode version

I have a NSString containing possible unwanted characters that I have to convert to the escaped unicode version. More specifically, I need to pass a JSON object (serialized as a string) to a UIWebView via it's script evaluation method, and some characters tend to raise a JS exception.

So I want to encode all characters mentioned to be unsafe by JSLint which are:


and replace them with their escaped equivalents.

What's the best way to do this?

UPDATE: Somehow \u2028 (line separator char) snuck in the JSON


Well, it's not exactly the solution I had in mind, but trimming is also a suitable option

  // Remove unsafe JSON characters
  if (jsonStr.length > 0) {
    NSMutableCharacterSet *unsafeSet = [NSMutableCharacterSet new];
    void (^addUnsafe)(NSInteger, NSInteger) = ^(NSInteger from, NSInteger to) {
      if (to > from) {
        [unsafeSet addCharactersInRange:NSMakeRange(from, (to - from) + 1)];
      } else {
        [unsafeSet addCharactersInRange:NSMakeRange(from, 1)];

    addUnsafe(0x0000, 0x001f);
    addUnsafe(0x007f, 0x009f);
    addUnsafe(0x00ad, 0);
    addUnsafe(0x0600, 0x0604);
    addUnsafe(0x070f, 0);
    addUnsafe(0x17b4, 0);
    addUnsafe(0x17b5, 0);
    addUnsafe(0x200c, 0x200f);
    addUnsafe(0x2028, 0x202f);
    addUnsafe(0x2060, 0x206f);
    addUnsafe(0xfeff, 0);
    addUnsafe(0xfff0, 0xffff);

    jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:unsafeSet] componentsJoinedByString:@""];

Need Your Help

Date format issue in ios7

ios iphone nsdateformatter

I am facing a a strange issue in date. i am getting varied results on the time format.

Title Heading for Tree R Package

r plot tree

I want to add a main title heading to the plot output of a tree model.