How to replace special characters with an escape character and the same special character. (How to use zoho.crm.searchRecords with special characters)

How to replace special characters with an escape character and the same special character. (How to use zoho.crm.searchRecords with special characters)

I couldn't find any documentation or posts about this issue, so I am posting my solution in case anyone else is looking for it. I had this problem because I was not able to use zoho.crm.searchRecords function with values that had special characters in the search string.

Input: "Some (String) that [has] ,,,,, <special> characters!"
Desired Output: "Some \(String\) that \[has\] \,\,\,\,\, \<special\> characters\!"

*code starts*

// the string you have
Name = "Some (String) that [has] ,,,,, <special> characters!"

// special characters you need to account for, add to this list as needed
special_chars = ['(', ')', '<', '>', '[', ']', '{', '}', '!', ',', '.'];

// loop all special characters
for each char in special_chars
{
    // add escape character with an underscore to the special character. You need the underscore because you cannot close the quotes if you use "\"
    oldSpecial = "\_" + char;
    
    
    // remove the underscore
    oldSpecial = oldSpecial.replaceAll("_", "");
    
    // add two escape characters to the underscore. You need the underscore because you cannot close the quotes if you use "\"
    newSpecial = "\\_" + char;
    
    // remove the underscore
    newSpecial = newSpecial.replaceAll("_", "");   
    
    // replace the single escape character with a double escape character
    Name = Name.replaceAll(oldSpecial, newSpecial);

}

info Name

*code ends*

Now you can use the searchRecords function with a string that has special characters. Note that underscore does not need the escape character before it.