Created
July 21, 2016 10:18
-
-
Save artemkrachulov/2a3d6fb9dcf6e2844ae19090877d0058 to your computer and use it in GitHub Desktop.
Strip whitespace characters from the beginning and ending for represented string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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