2

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

user635064
  • 6,219
  • 12
  • 54
  • 100

1 Answers1

4

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:

Community
  • 1
  • 1
Regexident
  • 29,441
  • 10
  • 93
  • 100
  • Thanks but is there a better way? because I have to do it for all these string: ~!@#$%^&*()_+=-\][{}|';:> &*()_+=-\][{}|';:"/.,<>? and something it would be very repetitive if i did it for all of these characters – user635064 Apr 07 '11 at 22:54
  • 1
    Updated my answer with a more appropriate category. – Regexident Apr 07 '11 at 23:06
  • `stringByAddingPercentEscapesUsingEncoding:` misses a *lot* of stuff. There are several other answers on this site with alternatives. – Dave DeLong Apr 07 '11 at 23:57
  • Thanks Dave, added a note along with a few SO links I found. – Regexident Apr 08 '11 at 09:49