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 with \', that is, when I print str I should get an output of Hello \'thanks\' bye. Without using double quotes, how do I achieve this with Apex?

1 Answer 1


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\\\''.

  • This is EXACTLY what I was looking for! Thank you!
    – Jay
    May 22, 2019 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .