Search code examples
javascriptobjective-cregexreplacensscanner

Porting the Javascript replace() function to Objective C


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?


Solution

  • 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.