A comprehensive, lightweight string extension for Swift

Related tags

Text SwiftString
Overview

SwiftString

CI Status Version License Platform Swift-2.1

SwiftString is a lightweight string extension for Swift. This library was motivated by having to search StackOverflow for common string operations, and wanting them to be in one place with test coverage.

Installation

SwiftString is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SwiftString"

Usage

import SwiftString

Methods

between(left, right)

"<a>foo</a>".between("<a>", "</a>") // "foo"
"<a><a>foo</a></a>".between("<a>", "</a>") // "<a>foo</a>"
"<a>foo".between("<a>", "</a>") // nil
"Some strings } are very {weird}, dont you think?".between("{", "}") // "weird"
"<a></a>".between("<a>", "</a>") // nil
 "<a>foo</a>".between("<a>", "<a>") // nil

camelize()

"os version".camelize() // "osVersion"
"HelloWorld".camelize() // "helloWorld"
"someword With Characters".camelize() // "somewordWithCharacters"
"data_rate".camelize() // "dataRate"
"background-color".camelize() // "backgroundColor"

capitalize()

"hello world".capitalize() // "Hello World"

chompLeft(string)

"foobar".chompLeft("foo") // "bar"
"foobar".chompLeft("bar") // "foo"

chompRight(string)

"foobar".chompRight("bar") // "foo"
"foobar".chompRight("foo") // "bar"

collapseWhitespace()

"  String   \t libraries are   \n\n\t fun\n!  ".collapseWhitespace() // "String libraries are fun !")

contains(substring)

"foobar".contains("foo") // true
"foobar".contains("bar") // true
"foobar".contains("something") // false

count(string)

"hi hi ho hey hihey".count("hi") // 3

decodeHTML()

"The Weekend &#8216;King Of The Fall&#8217;".decodeHTML() // "The Weekend ‘King Of The Fall’"
"<strong> 4 &lt; 5 &amp; 3 &gt; 2 .</strong> Price: 12 &#x20ac;.  &#64; ".decodeHTML() // "<strong> 4 < 5 & 3 > 2 .</strong> Price: 12 €.  @ "
"this is so &quot;good&quot;".decodeHTML() // "this is so \"good\""

endsWith(suffix)

"hello world".endsWith("world") // true
"hello world".endsWith("foo") // false

ensureLeft(prefix)

"/subdir".ensureLeft("/") // "/subdir"
"subdir".ensureLeft("/") // "/subdir"

ensureRight(suffix)

"subdir/".ensureRight("/") // "subdir/"
"subdir".ensureRight("/") // "subdir/"

indexOf(substring)

"hello".indexOf("hell"), // 0
"hello".indexOf("lo"), // 3
"hello".indexOf("world") // nil

initials()

"First".initials(), // "F"
"First Last".initials(), // "FL"
"First Middle1 Middle2 Middle3 Last".initials() // "FMMML"

initialsFirstAndLast()

"First Last".initialsFirstAndLast(), // "FL"
"First Middle1 Middle2 Middle3 Last".initialsFirstAndLast() // "FL"

isAlpha()

"fdafaf3".isAlpha() // false
"afaf".isAlpha() // true
"dfdf--dfd".isAlpha() // false

isAlphaNumeric()

"afaf35353afaf".isAlphaNumeric() // true
"FFFF99fff".isAlphaNumeric() // true
"99".isAlphaNumeric() // true
"afff".isAlphaNumeric() // true
"-33".isAlphaNumeric() // false
"aaff..".isAlphaNumeric() // false

isEmpty()

" ".isEmpty() // true
"\t\t\t ".isEmpty() // true
"\n\n".isEmpty() // true
"helo".isEmpty() // false

isNumeric()

"abc".isNumeric() // false
"123a".isNumeric() // false
"1".isNumeric() // true
"22".isNumeric() // true
"33.0".isNumeric() // true
"-63.0".isNumeric() // true

join(sequence)

",".join([1,2,3]) // "1,2,3"
",".join([]) // ""
",".join(["a","b","c"]) // "a,b,c"
"! ".join(["hey","who are you?"]) // "hey! who are you?"

latinize()

"šÜįéïöç".latinize() // "sUieioc"
"crème brûlée".latinize() // "creme brulee"

lines()

"test".lines() // ["test"]
"test\nsentence".lines() // ["test", "sentence"]
"test \nsentence".lines() // ["test ", "sentence"]

pad(n, string)

"hello".pad(2) // "  hello  "
"hello".pad(1, "\t") // "\thello\t"

padLeft(n, string)

"hello".padLeft(10) // "          hello"
"what?".padLeft(2, "!") // "!!what?"

padRight(n, string)

"hello".padRight(10) // "hello          "
"hello".padRight(2, "!") // "hello!!"

startsWith(prefix)

"hello world".startsWith("hello") // true
"hello world".startsWith("foo") // false

split(separator)

"hello world".split(" ")[0] // "hello"
"hello world".split(" ")[1] // "world"
"helloworld".split(" ")[0] // "helloworld"

times(n)

"hi".times(3) // "hihihi"
" ".times(10) // "          "

toBool()

"asdwads".toBool() // nil
"true".toBool() // true
"false".toBool() // false

toFloat()

"asdwads".toFloat() // nil
"2.00".toFloat() // 2.0
"2".toFloat() // 2.0

toInt()

"asdwads".toInt() // nil
"2.00".toInt() // 2
"2".toInt() // 2

toDate()

"asdwads".toDate() // nil
"2014-06-03".toDate() // NSDate

toDateTime()

"asdwads".toDateTime() // nil
"2014-06-03 13:15:01".toDateTime() // NSDate

toDouble()

"asdwads".toDouble() // nil
"2.00".toDouble() // 2.0
"2".toDouble() // 2.0

trimmedLeft()

"        How are you? ".trimmedLeft() // "How are you? "

trimmedRight()

" How are you?   ".trimmedRight() // " How are you?"

trimmed()

"    How are you?   ".trimmed() // "How are you?"

slugify()

"Global Thermonuclear Warfare".slugify() // "global-thermonuclear-warfare"
"Crème brûlée".slugify() // "creme-brulee"

stripPunctuation()

"My, st[ring] *full* of %punct)".stripPunctuation() // "My string full of punct"

substring(startIndex, length)

"hello world".substring(0, length: 1) // "h"
"hello world".substring(0, length: 11) // "hello world"

[subscript]

"hello world"[0...1] // "he"
"hello world"[0..<1] // "h"
"hello world"[0] // "h"
"hello world"[0...10] // "hello world"

Author

Andrew Mayne, [email protected]

License

SwiftString is available under the MIT license. See the LICENSE file for more info.

Comments
  • Added 2 functions with tests and ReadMe info:

    Added 2 functions with tests and ReadMe info:

    • initials: Get the initials of all the words in a string
    • initialsFirstAndLast: Gets the initial of the first word and the initial of the last word of the string
    opened by spinach 1
  • Better conditions for `between`

    Better conditions for `between`

    Add documentation for between and handle the conditions where the two bookends are the same and the if there is no text between the bookends. Updated tests.

    opened by Abizern 1
  • Stash formatters in thread-local storage for performance.

    Stash formatters in thread-local storage for performance.

    Hey, NS*Formatter initialization is expensive. This PR caches formatters in thread-local storage.

    Tested a few methods on my MBP with -Os optimization:

    | Method | Speedup | | --- | --- | | .isNumeric() | 84% | | .toDouble() | 51% | | .toDate() | 58% |

    With thousands of strings, the speedup amounts to seconds.

    opened by peyton 0
  • Carthage support + XCTests

    Carthage support + XCTests

    @amayne I used your code to learn how to create Carthage packages using Thoughtbot's tutorial on creating frameworks.

    I have also turned your phenomenal list of examples into XCTests that verify the code does what it's intended to do. The two functions that return NSDate are not as well-covered as the rest. I have to dig into my notes on how the class works.

    Finally, I have tweaked the setup for Travis according to Carthage's instructions.

    I have not properly tested support of Cocoapods, but I have edited the paths in the .podspec file, so that should probably do it.

    This would close #5, making the package more robust.

    opened by catalandres 0
  • cocoapods 1.0.0 beta 6 support

    cocoapods 1.0.0 beta 6 support

    Updated to cocoapods 1.0.0 beta 6 from 0.39.0. Can't compile your lib as pod.

    got this error:

    error: SwiftString/SwiftString.bundle: No such file or directory
    

    From what I see you have these lines in .podspec

    s.resource_bundles = {
        'SwiftString' => ['Pod/Assets/*.png']
      }
    

    As far as there is no image files under Pod/Assets/I assume new cocoapods doesn't build anything to bundle.

    opened by xNekOIx 0
  • Make camelize consistently use lower camel case

    Make camelize consistently use lower camel case

    Looks like camelize was only ensuring that the first letter was lowercase when there was only one word. This applies does that for the multi-word case. I also removed an unnecessary cast to NSString and moved the call to lowercaseString to the end so that it only needs to be applied to the one character.

    opened by raylillywhite 0
  • " ".trimmed() does not trim

    print(" ".trimmed())
    print(" ".trimmed().characters.count) // returns 1
    print("  ".trimmed())
    print("  ".trimmed().characters.count) // returns 2
    print("   ".trimmed())
    print("   ".trimmed().characters.count) // returns 3
    

    Would expect all to return a "" string with 0 length

    opened by MaximusMcCann 0
  • Add new extension method rindexOf

    Add new extension method rindexOf

    rindexOf is used to get the last occurrence of the given substring. It is a reverse version of indexOf.

    Sample usage as below: rindexOf(substring)

    "hello".rindexOf("hell"), // 0
    "helloll".rindexOf("ll"), // 5
    "hello".rindexOf("world") // nil
    

    Test case for the new method is provided.

    opened by enix223 0
  • Swift 2.3 and 3 support

    Swift 2.3 and 3 support

    Hello there,

    I would like to know if someone's already working on updating this library, and if not if you intend to, I would also like to help in this.

    Thank you, tiferrei

    opened by tiferrei 11
Owner
Andrew Mayne
Andrew Mayne
Great Swift String Pluralize Extension

Pluralize.swift Great Swift String Pluralize Extension case-insensitive tons of rules for irregular nouns (plural form) supports uncountable nouns all

Joshua Arvin Lat 193 Nov 8, 2022
BonMot is a Swift attributed string library

BonMot (pronounced Bon Mo, French for good word) is a Swift attributed string library. It abstracts away the complexities of the iOS, macOS, tvOS, and

Rightpoint 3.4k Dec 30, 2022
Croc is a swift emoji string parsing library

Croc is a library for parsing emojis on iOS. It provides a simple and lightweight interface for detecting, generating, categorizing and managing emoji characters, making emoji-powered features an easy task for developers.

Joe Kalash 127 Nov 20, 2022
👩‍🎨 Elegant Attributed String composition in Swift sauce

Elegant Attributed String composition in Swift sauce SwiftRichString is a lightweight library which allows to create and manipulate attributed strings

Daniele Margutti 2.9k Jan 5, 2023
🌍⏩📄 Convert ISO8859 1-16 Encoded Text to String in Swift. Supports iOS, tvOS, watchOS and macOS.

ISO8859 Convert ISO8859 1-16 Encoded Text to String in Swift. Usage let encoding = ISO8859.part1 let string = String([...], iso8859Encoding: encoding)

Devran Cosmo Uenal 18 Jan 2, 2023
A Cross-Platform String and Regular Expression Library written in Swift.

Guitar ?? A Cross-Platform String and Regular Expression Library written in Swift. About This library seeks to add common string manipulation function

Arthur Ariel Sabintsev 659 Dec 27, 2022
Swift emoji string parsing library

Croc is a library for parsing emojis on iOS. It provides a simple and lightweight interface for detecting, generating, categorizing and managing emoji

Joe Kalash 125 Sep 27, 2021
More powerful label, attributed string builder and text parser.

DDText More powerful label, attributed string builder and text parser. DDLabel More powerful label than UILabel, using TextKit. It supports features b

Daniel 16 Nov 8, 2022
String (and more) validation for iOS

Swift Validators ?? String validation for iOS. Contents Installation Walkthrough Usage Available validators License ReactiveSwift + SwiftValidators Wa

George Kaimakas 241 Nov 13, 2022
Easy string decoration with styles

StyleDecorator Design string simply by linking attributes. Example Create Decorator with specific Style and link it at the end of needed string or wra

Dmytro Pylypenko 15 Nov 4, 2021
Easy Attributed String Creator

The main idea of this project is to have an online tool to be able to visually add formatting to a text and get back a swift and/or objective-c code t

Andres Canal 283 Dec 27, 2022
🎗 Super lightweight ISO8601 Date Formatter in Swift

ISO8601 ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut mana

Khoa 19 May 12, 2020
Lightweight library to set an Image as text background. Written in swift.

![](https://img.shields.io/badge/Swift 2-compatible-4BC51D.svg?style=flat-square) Simple and light weight UIView that animate text with an image. Demo

Lucas Ortis 552 Sep 9, 2022
CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS

CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS. Features ?? Lightweight CodeMirror wrapper (build 5.52.2) ✅ 100% Native Swi

Proxyman 86 Dec 30, 2022
VEditorKit - Lightweight and Powerful Editor Kit built on Texture(AsyncDisplayKit)

VEditorKit provides the most core functionality needed for the editor. Unfortunately, When combined words are entered then UITextView selectedRange will changed and typingAttribute will cleared. So, In combined words case, Users can't continue typing the style they want.

David Ha 471 Dec 27, 2022
SZMentionsSwift is a lightweight mentions library for iOS.

SZMentionsSwift is a lightweight mentions library for iOS. This library was built to assist with the adding, removing and editing of a mention within a textview.

Steven Zweier 122 Dec 12, 2022
A lightweight fuzzy-search library, with zero dependencies

Fuse What is Fuse? Fuse is a super lightweight library which provides a simple way to do fuzzy searching. Usage Example 1 let fuse = Fuse() let result

Kiro Risk 864 Dec 29, 2022
Fully open source text editor for iOS written in Swift.

Edhita Fully open source text editor for iOS written in Swift. http://edhita.bornneet.com/ What Edhita means? Edhita (Romaji) == エディタ (Katakana) == Ed

Tatsuya Tobioka 1.2k Jan 1, 2023