Skip to content

Instantly share code, notes, and snippets.

@artemkrachulov
Created July 21, 2016 10:18
Show Gist options
  • Save artemkrachulov/2a3d6fb9dcf6e2844ae19090877d0058 to your computer and use it in GitHub Desktop.
Save artemkrachulov/2a3d6fb9dcf6e2844ae19090877d0058 to your computer and use it in GitHub Desktop.
Strip whitespace characters from the beginning and ending for represented string.
//
// String+trim.swift
//
// Created by Artem Krachulov
// Copyright (c) 2016 Artem Krachulov. All rights reserved.
// Gist:
// http://www.artemkrachulov.com
//
import UIKit
extension String {
/// Strip whitespace characters from the beginning and ending for represented string.
///
/// Usage:
///
/// " Hello, world ".trim() // "Hello, world"
/// " ".trim() // ""
/// "".trim() // ""
public func trim() -> String {
guard !isEmpty else { return "" }
do {
let expression = try NSRegularExpression(pattern: "^\\s+|\\s+$|\\s+(?=\\s)", options: NSRegularExpressionOptions.CaseInsensitive)
return expression.stringByReplacingMatchesInString(self, options: [], range: NSMakeRange(0, characters.count), withTemplate: "")
} catch {
return self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment