Skip to content

Commit d6eb480

Browse files
committed
Merge pull request #44 from hdgarrood/stripSuffix
Add `stripSuffix`
2 parents 6e9f7c5 + e786b5c commit d6eb480

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

docs/Data/String.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ string left after removing it, as a Just value. Otherwise, return Nothing.
8989
* `stripPrefix "http:" "http://purescript.org" == Just "//purescript.org"`
9090
* `stripPrefix "http:" "https://purescript.org" == Nothing`
9191

92+
#### `stripSuffix`
93+
94+
``` purescript
95+
stripSuffix :: String -> String -> Maybe String
96+
```
97+
98+
If the string ends with the given suffix, return the portion of the
99+
string left after removing it, as a Just value. Otherwise, return Nothing.
100+
* `stripSuffix ".exe" "psc.exe" == Just "psc"`
101+
* `stripSuffix ".exe" "psc" == Nothing`
102+
92103
#### `fromCharArray`
93104

94105
``` purescript
@@ -198,8 +209,9 @@ of the string for which the predicate holds.
198209
split :: String -> String -> Array String
199210
```
200211

201-
Returns the substrings of the first string separated along occurences
202-
of the second string.
212+
Returns the substrings of the second string separated along occurences
213+
of the first string.
214+
* `split " " "hello world" == ["hello", "world"]`
203215

204216
#### `toCharArray`
205217

src/Data/String.purs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ module Data.String
2424
, drop
2525
, dropWhile
2626
, stripPrefix
27+
, stripSuffix
2728
, split
2829
, toCharArray
2930
, toLower
@@ -105,6 +106,18 @@ stripPrefix prefix str =
105106
Just 0 -> Just $ drop (length prefix) str
106107
_ -> Nothing
107108

109+
-- | If the string ends with the given suffix, return the portion of the
110+
-- | string left after removing it, as a Just value. Otherwise, return Nothing.
111+
-- | * `stripSuffix ".exe" "psc.exe" == Just "psc"`
112+
-- | * `stripSuffix ".exe" "psc" == Nothing`
113+
stripSuffix :: String -> String -> Maybe String
114+
stripSuffix suffix str =
115+
case lastIndexOf suffix str of
116+
Just x | x == length str - length suffix ->
117+
Just $ take x str
118+
_ ->
119+
Nothing
120+
108121
-- | Converts an array of characters into a string.
109122
foreign import fromCharArray :: Array Char -> String
110123

0 commit comments

Comments
 (0)