Skip to content

Instantly share code, notes, and snippets.

@nickvelloff
Forked from RobertAudi/NSString+RAInflections.h
Last active January 29, 2016 15:30
Show Gist options
  • Save nickvelloff/5fb1c47521841aa510ee to your computer and use it in GitHub Desktop.
Save nickvelloff/5fb1c47521841aa510ee to your computer and use it in GitHub Desktop.
//
// Created by Robert Audi on 07/04/13.
// Updated on 08/21/14
//
#import <Foundation/Foundation.h>
@interface NSString (RAInflections)
- (NSString *)slugalize;
@end
//
// Created by Robert Audi on 07/04/13.
// Updated on 08/21/14
//
#import "NSString+RAInflections.h"
@implementation NSString (RAInflections)
/**
* Port of the slugalized helper created by @henrik
* https://github.com/RobertAudi/slugalizer
*/
- (NSString *)slugalize
{
NSString *separator = @"-";
NSMutableString *slugalizedString = [NSMutableString string];
NSRange replaceRange = NSMakeRange(0, self.length);
// Remove all non ASCII characters
NSError *nonASCIICharsRegexError = nil;
NSRegularExpression *nonASCIICharsRegex = [NSRegularExpression regularExpressionWithPattern:@"[^\\x00-\\x7F]+"
options:0
error:&nonASCIICharsRegexError];
slugalizedString = [[nonASCIICharsRegex stringByReplacingMatchesInString:self
options:0
range:replaceRange
withTemplate:@""] mutableCopy];
// Turn non-slug characters into separators
NSError *nonSlugCharactersError = nil;
NSRegularExpression *nonSlugCharactersRegex = [NSRegularExpression regularExpressionWithPattern:@"[^a-z0-9\\-_\\+]+"
options:NSRegularExpressionCaseInsensitive
error:&nonSlugCharactersError];
replaceRange = NSMakeRange(0, slugalizedString.length);
slugalizedString = [[nonSlugCharactersRegex stringByReplacingMatchesInString:slugalizedString
options:0
range:replaceRange
withTemplate:separator] mutableCopy];
// No more than one of the separator in a row
NSError *repeatingSeparatorsError = nil;
NSRegularExpression *repeatingSeparatorsRegex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"%@{2,}", separator]
options:0
error:&repeatingSeparatorsError];
replaceRange = NSMakeRange(0, slugalizedString.length);
slugalizedString = [[repeatingSeparatorsRegex stringByReplacingMatchesInString:slugalizedString
options:0
range:replaceRange
withTemplate:separator] mutableCopy];
// Remove leading/trailing separator
slugalizedString = [[slugalizedString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:separator]] mutableCopy];
return [slugalizedString lowercaseString];
}
@end
extension String {
func slugalize() -> String {
return NSString(string: self).slugalize()
}
}
@nickvelloff
Copy link
Author

Addes Swift implementation. Be sure to add the #import "NSString+RAInflections.h" to your bridge header file.

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