From c50b00f6769b5132038a22c194b09e0f4b28efec Mon Sep 17 00:00:00 2001 From: Richard Carlsson Date: Thu, 30 Nov 2023 14:43:03 +0100 Subject: [PATCH] Use modern Erlang string functions in Data.String.Common Fixes broken use of regexp in trim and Latin-1 limitations in replace. --- src/Data/String/Common.erl | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Data/String/Common.erl b/src/Data/String/Common.erl index 70c2c4c..f8e8e63 100644 --- a/src/Data/String/Common.erl +++ b/src/Data/String/Common.erl @@ -2,11 +2,12 @@ -export(['_localeCompare'/5, replace/3, replaceAll/3, split/2, toLower/1, toUpper/1, trim/1, joinWith/2]). '_localeCompare'(_Lt,_Eq,_Gt,_S1,_S2) -> error("not implemented"). -replace(S1,S2,S3) -> iolist_to_binary(string:replace(S3, S1, S2)). -replaceAll(S1,S2,S3) -> iolist_to_binary(string:replace(S3, S1, S2, all)). + +replace(S1,S2,S3) -> unicode:characters_to_binary(string:replace(S3, S1, S2)). + +replaceAll(S1,S2,S3) -> unicode:characters_to_binary(string:replace(S3, S1, S2, all)). split(Sep,S) -> - Split = string:split(S, Sep, all), Res = case {Sep,S} of {<<>>,<<>>} -> []; %% string:split says [<<>>] but JS says [] {<<>>,_} -> @@ -14,18 +15,15 @@ split(Sep,S) -> lists:map(fun (C) -> unicode:characters_to_binary([C], utf8) end, unicode:characters_to_list(S, utf8)); %% {_,<<>>} behaves the same in JS vs string:split - _ -> Split + _ -> string:split(S, Sep, all) end, array:from_list(Res). -% TODO ugh -toLower(S) -> unicode:characters_to_binary(string:to_lower(unicode:characters_to_list(S))). +toLower(S) -> string:lowercase(S). -toUpper(S) -> unicode:characters_to_binary(string:to_upper(unicode:characters_to_list(S))). +toUpper(S) -> string:uppercase(S). -trim(S) -> re:replace(S, "^\\s*(.*?)\\s*$","\\1", [{return, binary}]). +trim(S) -> string:trim(S). joinWith(S, XS) -> - XS1 = lists:map(fun unicode:characters_to_list/1, array:to_list(XS)), - Res = string:join(XS1, unicode:characters_to_list(S)), - unicode:characters_to_binary(Res). + unicode:characters_to_binary(lists:join(S, array:to_list(XS))).