From b5720e2b3fd2daa367264ca6412db397e18257ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gutyina=20Gerg=C5=91?= Date: Tue, 27 May 2025 22:21:08 +0200 Subject: [PATCH] lib/strings: init replaceString --- lib/default.nix | 1 + lib/strings.nix | 35 +++++++++++++++++++++++++++++++++++ lib/tests/misc.nix | 11 +++++++++++ 3 files changed, 47 insertions(+) diff --git a/lib/default.nix b/lib/default.nix index 63e02882e2c3..6f8530296044 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -309,6 +309,7 @@ let stringLength substring isString + replaceString replaceStrings intersperse concatStringsSep diff --git a/lib/strings.nix b/lib/strings.nix index ba8c47b69037..ca97e5b4658b 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -332,6 +332,41 @@ rec { */ concatLines = concatMapStrings (s: s + "\n"); + /** + Given string `s`, replace every occurrence of the string `from` with the string `to`. + + # Inputs + + `from` + : The string to be replaced + + `to` + : The string to replace with + + `s` + : The original string where replacements will be made + + # Type + + ``` + replaceString :: string -> string -> string -> string + ``` + + # Examples + :::{.example} + ## `lib.strings.replaceString` usage example + + ```nix + replaceString "world" "Nix" "Hello, world!" + => "Hello, Nix!" + replaceString "." "_" "v1.2.3" + => "v1_2_3" + ``` + + ::: + */ + replaceString = from: to: replaceStrings [ from ] [ to ]; + /** Repeat a string `n` times, and concatenate the parts into a new string. diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 0d8377ec6006..437714a2822e 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -91,6 +91,7 @@ let range recursiveUpdateUntil removePrefix + replaceString replicate runTests setFunctionArgs @@ -497,6 +498,11 @@ runTests { expected = "/usr/include:/usr/local/include"; }; + testReplaceStringString = { + expr = strings.replaceString "." "_" "v1.2.3"; + expected = "v1_2_3"; + }; + testReplicateString = { expr = strings.replicate 5 "hello"; expected = "hellohellohellohellohello"; @@ -1728,6 +1734,11 @@ runTests { ]; }; + testReplaceString = { + expr = replaceString "world" "Nix" "Hello, world!"; + expected = "Hello, Nix!"; + }; + testReplicate = { expr = replicate 3 "a"; expected = [