0

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

7

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');
  • Thanks @sfdcfox – Sisir Mar 29 at 21:31
0

Have you tried this one:

    identifier.replaceAll('\'','\\'')
  • It did not work @RRI. – Sisir Mar 29 at 21:34

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.