Search code examples
nsis

NSIS - Remove leading and trailing whitespaces from a string


I want to trim my textbox value in NSIS, for that i have used the below link

http://nsis.sourceforge.net/Remove_leading_and_trailing_whitespaces_from_a_string Problem with my solution is, above example remove the entire text followed by the text say example my text is something like this " First Name ". when i call the trim method it removes Entire Name itself and giving the result as "First". But i want to remove only leading and trailing whitespace. Not the inbetween spaces.

How can i achieve this ?


Solution

  • Works for me:

    Function Trim
        Exch $R1 ; Original string
        Push $R2
    Loop:
        StrCpy $R2 "$R1" 1
        StrCmp "$R2" " " TrimLeft
        StrCmp "$R2" "$\r" TrimLeft
        StrCmp "$R2" "$\n" TrimLeft
        StrCmp "$R2" "$\t" TrimLeft
        GoTo Loop2
    TrimLeft:
        StrCpy $R1 "$R1" "" 1
        Goto Loop
    Loop2:
        StrCpy $R2 "$R1" 1 -1
        StrCmp "$R2" " " TrimRight
        StrCmp "$R2" "$\r" TrimRight
        StrCmp "$R2" "$\n" TrimRight
        StrCmp "$R2" "$\t" TrimRight
        GoTo Done
    TrimRight:
        StrCpy $R1 "$R1" -1
        Goto Loop2
    Done:
        Pop $R2
        Exch $R1
    FunctionEnd
    !define Trim "!insertmacro Trim"
     !macro Trim ResultVar String
      Push "${String}"
      Call Trim
      Pop "${ResultVar}"
    !macroend
    
    
    Section
    
    ${Trim} $0 " First Name "
    MessageBox mb_ok "|$0|"
    
    SectionEnd
    

    Maybe you could edit your question to include example code that fails?