artemkrachulov
7/21/2016 - 10:18 AM

Strip whitespace characters from the beginning and ending for represented string.

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
    }
  }
}