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

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() .


There's a method for this: String.escapeSingleQuotes. It's meant to be used to protect against SOQL injection.

Identifier = String.escapeSingleQuotes('string\'s length');

Have you tried this one:

  • It did not work @RRI. – Sisir Mar 29 '19 at 21:34

The replacement does not modify the string in place, but rather returns the modified value.

Instead of:



 identifier = identifier.replaceAll('\'','\\'')

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.