String Functions in PureScript
module Main where
import Prelude
import Effect.Console (log)
import Data.String as S
-- We alias `log` to a shorter name as we'll use it a lot below.
p = log
main = do
-- Here's a sample of the functions available in the `Data.String` module.
-- Since these are functions from the module, not methods on the string object itself,
-- we need to pass the string in question as an argument to the function.
-- You can find more functions in the `Data.String` module documentation.
p $ "Contains: " <> show (S.contains (S.Pattern "es") "test")
p $ "Count: " <> show (S.count (S.Pattern "t") "test")
p $ "StartsWith: " <> show (S.startsWith (S.Pattern "te") "test")
p $ "EndsWith: " <> show (S.endsWith (S.Pattern "st") "test")
p $ "IndexOf: " <> show (S.indexOf (S.Pattern "e") "test")
p $ "Join: " <> S.joinWith "-" ["a", "b"]
p $ "Repeat: " <> S.replicate 5 "a"
p $ "Replace: " <> S.replace (S.Pattern "o") (S.Replacement "0") "foo"
p $ "Replace: " <> S.replaceAll (S.Pattern "o") (S.Replacement "0") "foo"
p $ "Split: " <> show (S.split (S.Pattern "-") "a-b-c-d-e")
p $ "ToLower: " <> S.toLower "TEST"
p $ "ToUpper: " <> S.toUpper "test"The standard library’s Data.String module provides many useful string-related functions. Here are some examples to give you a sense of the module.
In PureScript, string manipulation functions are typically found in the Data.String module. We import this module and alias it as S for brevity. We also import the Effect.Console module to use the log function for output.
Note that PureScript uses different function names for some operations compared to other languages:
containsis used instead ofContainsstartsWithandendsWithare used instead ofHasPrefixandHasSuffixindexOfis used instead ofIndexjoinWithis used instead ofJoinreplicateis used instead ofRepeatreplaceandreplaceAllare used instead of a singleReplacefunction with a count parameter
Also, PureScript uses Pattern and Replacement wrappers for string patterns and replacements in some functions.
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
$ pulp run
Contains: true
Count: 2
StartsWith: true
EndsWith: true
IndexOf: 1
Join: a-b
Repeat: aaaaa
Replace: f0o
Replace: f00
Split: ["a","b","c","d","e"]
ToLower: test
ToUpper: TESTThis demonstrates various string operations available in PureScript’s standard library.