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);
0

4 Answers 4

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

0
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');
0
0

Have you tried this one:

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

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

Instead of:

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

Use:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .