Apex – How to Replace Single Quote with Backslash in Apex Code

i have string variable called "Identifier" which has apostrophe in it.

example: Identifier = "string's length"

i need to replace this apostrophe with "\'"

the result should be Identifier = "string\'s length"

finally i have to use this string variable in a database.query();

for example: below is the query string

String query = 'Select Id, Identifier__c from CustomObj__c where Identifier__c =' +Identifier;

And use this query in database.query() like below

database.query(query);

Best Answer

String str = 'L\'Oreal'; //<-- get the escaped name

System.debug(str); // <--debug output: L'Oreal

String strEsc = String.escapeSingleQuotes(str); //<-- pass through escape method

System.debug(strEsc); //<-- output: L\'Oreal

String wQuotes = '\'%'+strEsc+'%\''; //<-- try to create just the like string

System.debug(wQuotes);  //<--output: '%L\'Oreal%'

List<Account> accts = Database.query('Select Id FROM Account WHERE Name like \'%'+strEsc+'%\'');
//debug of SOQL statement reads: Select Id FROM Account WHERE Name like '%L\'Oreal%'

give try this once. there is one method that do it for you, escapeSingleQuotes() .

Related Topic