aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/gleam/string.gleam21
-rw-r--r--test/gleam/string_test.gleam30
2 files changed, 51 insertions, 0 deletions
diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam
index 3cec7d2..d574242 100644
--- a/src/gleam/string.gleam
+++ b/src/gleam/string.gleam
@@ -785,3 +785,24 @@ pub fn last(s: String) -> Option(String) {
_ -> Some(slice(s, length(s) - 1, 1))
}
}
+
+/// Creates a new `String` with the first grapheme in the input `String`
+/// converted to uppercase and the remaining graphemes to lowercase.
+///
+/// ## Examples
+///
+/// ```gleam
+/// > capitalize("mamouna")
+/// "Mamouna"
+/// ```
+///
+pub fn capitalize(s: String) -> String {
+ let first =
+ slice(s, 0, 1)
+ |> uppercase
+ let rest =
+ slice(s, 1, length(s))
+ |> lowercase
+
+ append(to: first, suffix: rest)
+}
diff --git a/test/gleam/string_test.gleam b/test/gleam/string_test.gleam
index 8ad1080..14b034c 100644
--- a/test/gleam/string_test.gleam
+++ b/test/gleam/string_test.gleam
@@ -388,3 +388,33 @@ pub fn last_test() {
|> string.last
|> should.equal(Some(" "))
}
+
+pub fn capitalize_test() {
+ ""
+ |> string.capitalize
+ |> should.equal("")
+
+ "gleam"
+ |> string.capitalize
+ |> should.equal("Gleam")
+
+ "GLEAM"
+ |> string.capitalize
+ |> should.equal("Gleam")
+
+ "g l e a m"
+ |> string.capitalize
+ |> should.equal("G l e a m")
+
+ "1GLEAM"
+ |> string.capitalize
+ |> should.equal("1gleam")
+
+ "_gLeAm1"
+ |> string.capitalize
+ |> should.equal("_gleam1")
+
+ " gLeAm1"
+ |> string.capitalize
+ |> should.equal(" gleam1")
+}