NSString encoding special characters like !@#$%^&

2019-02-15 16:14发布

问题:

How can i encode my NSString so all the special character for example & becomes &amp and ' becomes &apos?

I am not sure if encoding is the right word for it so please correct me if I am wrong.

Thanks

回答1:

What you are talking about is called HTML Entities.

There exists a category claiming to solve this: NSString+HTML.

For URL Escaping (while we're at it) use this:

@nterface NSString (Escaping)

- (NSString *)percentEscapedString
- (NSString *)percentUnescapedString

@end

@implementation NSString (Escaping)

- (NSString *)percentEscapedString {
    return [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)percentUnescapedString {
    return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end

Edit: As Dave pointed out weaknesses in my references solution, here are some related questions with lots of other solutions:

  • Objective C HTML escape/unescape
  • HTML character decoding in Objective-C / Cocoa Touch