IndexOf Function

The IndexOf function returns the character position in a variable using a string value to search. A good use case is that the IndexOf function can be used as to search or find within a string variable.

For example, if I only wanted update a string that had the color “red” to “blue”, IndexOf can be used as the string to search. If any number returned is greater than 0, then “red” exists in that string — since this function returns the character position. In conjunction a If function, a different output can be shown. See example below. (Note that this specific example can also be accomplished with a Replace function. )

Syntax:

                    

IndexOf(1,2)
1 = String value to evaluate (can be a variable)
2 = Search value to return the character position

                

Example:

                    

%%[
var @string 
set @string = “The paint color is red.”
set @paintColor = IndexOf(@string, “red”)

if @paintColor > 0 then
  set @string = “The paint color is blue”
endif

]%%
IndexOf Character Position: %%=v(@paintColor)=%%
Output: %%=v(@string)=%%

Output:

Character Position: 20
Output: The paint color is blue.

Explanation:

The IndexOf function evaluates the string variable @string with the value of “The paint color is red.” In the IndexOf function, we are using the value of “red” to return the character position if the word “red” exists in the string. Because the word “red” is in the string, the function returns the character position of 20.

The if statement checks to see if the IndexOf value is greater than 0 — if it is greater than 0 then show a different value for the @string variable.

Leave a Reply

Your email address will not be published. Required fields are marked *