Replace single quotes
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 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?
To replace quotes 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\''.