AutoHotkey – StrReplace()
StrReplace() replaces a substring in a string.
Parameters
StrReplace( Haystack, Needle, [ReplaceText, OutPutVarCount, Limit])
- Haystack: where is the replacement being made
- Needle: the string you want to replace
- ReplaceText: the replacement text, by default: “”
- OutPutVarCount: by default, it is 0, it can store the number of replacements
- Limit: limits the number of replacements
Return value
The function returns the replaced text/string. If no replacement has done then it will return the Haystack.
Examples
Replace a substring in variable/string.
strg := "Hello AutoHotkey!"
MsgBox % StrReplace(strg, "AutoHotkey", "World") ; hello World
Replace semicolons with tabulators in a CSV file.
; create a dummy csv file
FilePath := % A_Desktop "/" "test-StrReplace.csv"
FileAppend, % "1;001;A" "`n"
. "2;002;B", % FilePath
FileRead, File, % FilePath
FileDelete, % FilePath
MsgBox % File
File := StrReplace(File, ";", "`t")
MsgBox % File
How to delete something from a string?
strg := "...Hello World!..."
MsgBox % StrReplace(strg, "...")
Multiple replacement
strg := "... World."
;strg := StrReplace(strg, ".", "!") -> this will replace all period characters
strg := StrReplace(strg, "...", "Hello")
strg := StrReplace(strg, ".", "!" )
Msgbox % strg
One liner, less readable alternative
strg := StrReplace( StrReplace("... World.", "...", "Hello"), ".", "!" )
Msgbox % strg