1

Im trying to port over some Javascript code into Objective C, and I'm wondering what is the best approach for the Javascript .replace() function.

My javascript looks like this:

str = str.replace(/(\r\n|\r|\n)/g,'_r');

How would I achieve this with NSRegularExpression?

Or would I be better off using a NSScanner to parse through the strings and then replaceCharactersInRange: to replace the characters?

Jimmery
  • 9,783
  • 25
  • 83
  • 157
  • Can't you do the same thing with `stringByReplacingOccurrencesOfString:withString:`? – woz Jun 19 '13 at 15:54
  • woah - I wasnt even aware such a method existed, is this a part of NSString? And will it work on things like new lines? Thanks for the heads up! – Jimmery Jun 19 '13 at 15:56
  • Yep! It's in [the docs](http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSString_Class/Reference/NSString.html). Newlines should work fine. If you just want to strip all newlines and carriage returns there's also `[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]`. I'll post this as an answer. – woz Jun 19 '13 at 16:01

1 Answers1

1

You're in luck! NSString already has stringByReplacingOccurrencesOfString:withString:. It should work fine with new lines. Also, if you just want to strip all newlines and carriage returns, you can use:

[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

NSString comes with all kinds of things, and they are all documented here.

woz
  • 10,888
  • 3
  • 34
  • 64