Skip to content

Instantly share code, notes, and snippets.

@PadraigK
Last active August 29, 2015 13:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PadraigK/9844892 to your computer and use it in GitHub Desktop.
Save PadraigK/9844892 to your computer and use it in GitHub Desktop.
Quick and dirty implementation of Shaun Inman's 'Widont' in Cocoa
// Example:
//
// Widont makes the last space non-breaking
// so you don't end up with one word on its
// own.
//
// Widont makes the last space non-breaking
// so you don't end up with one word on
// its own.
//
// More Info:
// http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin
- (NSString *)stringByReplacingLastSpaceWithNonBreakingSpace
{
NSRange lastSpaceRange = [self rangeOfString:@" " options:NSBackwardsSearch];
NSUInteger minNumberOfWordsBeforeReplacing = 4;
if (lastSpaceRange.location!=NSNotFound) {
NSString *noSpaces = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([self length]-[noSpaces length] >= minNumberOfWordsBeforeReplacing-1) {
return [self stringByReplacingCharactersInRange:lastSpaceRange withString:@" "];
}
}
return self;
}
@PadraigK
Copy link
Author

Added a small tweak to make sure we only make the last space non-breaking if it's not the first space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment