I need to replace single quotes. However, I cannot use the " double quote character. Therefore, I cannot do something like this:

String s = "Hello 'thanks' bye";
    s = s.replaceAll("'", "\\'");
    // Hello \'thanks\' bye

I need to replace the single quotes in str by \', that is, when I print str I should get output as Welcome \'thanks\' How are you. Without using double quotes, how do I achieve this with Apex?


There is a built-in method String.escapeSingleQuotes() that handles this need nicely. From the documentation, an example:

String s = '\'Hello Jason\'';
system.debug(s); // Outputs 'Hello Jason'
String escapedStr = String.escapeSingleQuotes(s);
// Outputs \'Hello Jason\'
// Escapes the string \\\' to string \'
system.assertEquals('\\\'Hello Jason\\\'', escapedStr); 

Bear in mind that when writing literal strings in Apex you can include single quotes by escaping them with a backslash \, and to include a literal backslash you must escape it too. That's why the last line has '\\\'Hello Jason\\\''.

| improve this answer | |
  • This is EXACTLY what I was looking for! Thank you! – Jay May 22 '19 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.