StringReplace

Replaces the specified substring with a new string.

StringReplace, OutputVar, InputVar, SearchText [, ReplaceText, ReplaceAll?]

 

Parameters

OutputVar The name of the variable in which to store the result of the replacement process.
InputVar The name of the variable whose contents will be read from. Do not enclose the name in percent signs unless you want the contents of the variable to be used as the name.
SearchText The string to search for. Matching is not case sensitive unless StringCaseSense has been turned on.
ReplaceText SearchText will be replaced with this text. If omitted or blank, SearchText will be replaced with blank (empty). In other words, it will be omitted from OutputVar.
ReplaceAll?

If omitted, only the first occurrence of SearchText will be replaced. But if this parameter is 1, A, or All, all occurrences will be replaced.

In v1.0.25.05+, the word UseErrorLevel may also be present, which causes ErrorLevel to be given the number occurrences replaced (0 if none). Although UseErrorLevel implies "All", more than one word may be present as in this example: AllSlow UseErrorLevel

In v1.0.25+, a faster replacement method is used when all of the following are true: 1) The ALL mode is in effect; 2) InputVar contains more than 5000 characters; 3) SearchText occurs more than 20 times; and 4) SearchText is not the same length as ReplaceText (since in that case, the slow method performs just as quickly).

This faster method temporarily uses additional memory (proportional to the size of InputVar). If the system has insufficient memory, the command automatically reverts to the slow method. To unconditionally prevent the use of additional memory, specify the word AllSlow instead of All. Note that AllSlow may be unacceptably slow if InputVar contains thousands of occurrences of SearchText.

 

ErrorLevel

ErrorLevel is set to 1 if SearchText could not be found within InputVar, or 0 otherwise. The exception to this is when ReplaceAll includes the string UseErrorLevel, in which case which causes ErrorLevel is given the number occurrences replaced (0 if none).

 

Remarks

For this and all other commands, OutputVar is allowed to be the same variable as an InputVar.

The built-in variables %A_Space% and %A_Tab% contain a single space and a single tab character, respectively. They are useful when searching for spaces and tabs alone or at the beginning or end of SearchText.

 

Related

IfInString, StringLeft, StringRight, StringMid, StringTrimLeft, StringTrimRight, StringLen, StringLower, StringUpper, StringGetPos, if var is type

 

Examples

; Remove all CR+LF's from the clipboard contents:
StringReplace, clipboard, clipboard, `r`n, , All

; Replace all spaces with pluses:
StringReplace, NewStr, OldStr, %A_SPACE%, +, All

; Remove all blank lines from the text in a variable:
Loop
{
    StringReplace, MyString, MyString, `r`n`r`n, `r`n, UseErrorLevel
    if ErrorLevel = 0  ; No more replacements needed.
        break
}