2

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("'", "\\'");
System.out.println(s);
    // 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

7

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\'
system.debug(escapedStr); 
// 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\\\''.

1
  • This is EXACTLY what I was looking for! Thank you!
    – Jay
    Commented 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 .