With the newer StrReplace() function I noticed I could not use it with variables for whatever reason. And the documentation here: https://autohotkey.com/docs/commands/StringReplace.htm
is lacking an example. After a lot of tests, couldn't figure it out.
So I wrote a "polyfill" for StrReplace, complete with test code.
; Author: John Mark Isaac Madison
; EMAIL : J4M4I5M7@hotmail.com
; I_SRC : input source text
; I_OLD : old token to find
; I_NEW : new token to replace old with
FN_POLYFILL_STR_REPLACE(I_SRC, I_OLD, I_NEW)
{
;Check length of input parameters:
;--------------------------------------------;
L1 := StrLen(I_SRC)
L2 := StrLen(I_OLD)
L3 := StrLen(I_NEW)
if( !(L1 > 0) )
{
msgbox BAD_PARAM_#1:STR_REP
}
if( !(L2 > 0) )
{
msgbox BAD_PARAM_#2:STR_REP
}
if( !(L3 > 0) )
{
msgbox BAD_PARAM_#3:STR_REP
}
;--------------------------------------------;
OP := "" ;output string
f_ptr := 0 ;fill pointer
max_i := StrLen(I_SRC)
dx := 0 ;<--Loop counter / index
LOOP ;;[LOOP_START];;
{
dx++
if(dx > max_i)
{
break ;[BAIL_OUT_OF_LOOP]
}
h := FN_IS_TOKEN_HERE(I_SRC, I_OLD, dx)
;if(8==dx)
;{
; msgbox, HACK_8 dx[%dx%] h[%h%] I_SRC[%I_SRC%] I_OLD[%I_OLD%]
; src_len := StrLen( I_SRC )
; old_len := StrLen( I_OLD )
; msgbox src_len [%src_len%] old_len[%old_len%] I_OLD[%I_OLD%]
;}
if( h > 0)
{
;token found, replace it by concating
;the I_NEW onto output string:
OP := OP . I_NEW
;OP := OP . "[X]"
;msgbox : I_SRC[%I_SRC%] h[%h%] dx[%dx%]
;jump pointer to last character of
;the found token to skip over
;now irrelevant characters:
dx := h
;msgbox, DX: %dx%
}
else
if( 0 == h)
{
msgbox, "H_SHOULD_NOT_BE_ZERO"
}
else
if( h < 0 )
{
;concat character to output:
c := SubStr(I_SRC,dx,1)
OP := OP . c
}
} ;;[LOOP_END];;
msgbox OP : %OP%
;msgbox I_SRC[ %I_SRC%] I_OLD[ %I_OLD%] I_NEW[ %I_NEW%]
return OP ;;<--return output string
}
;Author: John Mark Isaac Madison
;EMAIL : J4M4I5M7@hotmail.com
;unit-test that will run when script boots up:
FN_POLYFILL_STR_REPLACE_TEST()
{
T1 := FN_POLYFILL_STR_REPLACE("WHAT_IS_UP","UP","DOWN")
;;msgbox, T1 : %T1%
i_src := "123_TOKEN_123"
i_old := "TOKEN"
i_new := "NEEEW"
T2 := FN_POLYFILL_STR_REPLACE(i_src,i_old,i_new)
;;msgbox, T2 : %T2%
;;msgbox, "POLYFILL_TEST_RAN"
i_src := "const IS_VARNAME"
i_old := "VARNAME"
i_new := "BASH"
T3 := FN_POLYFILL_STR_REPLACE(i_src,i_old,i_new)
;msgbox, T3 : %T3%
i_src := "123456VARNAME"
i_old := "VARNAME"
i_new := "AB"
T4 := FN_POLYFILL_STR_REPLACE(i_src,i_old,i_new)
if(T1 != "WHAT_IS_DOWN")
{
msgbox [PSR_TEST_FAIL#1]
}
if(T2 != "123_NEEEW_123")
{
msgbox [PSR_TEST_FAIL#2]
}
if(T3 != "const IS_BASH")
{
msgbox [PSR_TEST_FAIL#3]
}
if(T4 != "123456AB")
{
msgbox [PSR_TEST_FAIL#4]
}
return ;rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr;
}
FN_POLYFILL_STR_REPLACE_TEST()
Also, be aware that trimming out newlines in your data is harder than it
should be as well. And will be bound to throw a monkey wrench into whatever string parsing you are doing.