Search code examples
apex-code

Salesforce Apex String replacement funny business


Is anyone aware of how to differentiate between the characters '\"' and '"'? I am trying to pre-process a string and this statement confuses me.

system.assert(' "b" ' == ' "\"" '.replace('\"','b'); //FAILS, returns ' bbb '

Solution

  • In your example, Salesforce is essentially ignoring the backslash as illustrated here:

    system.assert('"' == '\"'); // yup
    system.assertEquals(1, '\"'.length()); // just one character
    system.assertEquals(1, '"'.length()); // just one character--the same one
    

    If your original string has a real backslash character in it, it's the backslash that you need to escape with another backslash like this:

    system.assertEquals(1, '\\'.length()); // just one character:  \
    system.assertEquals(2, '\\"'.length()); // two characters:  \"
    system.assert(' "b" ' == ' "\\"" '.replace('\\"','b'));