Saturday 2 July 2011

How to replace ' by \' in a string in Apex


Mostly This problem came in front when You need to use dynamic Query in which you can not use String with single quote so We have to replace ' in to \' 
There are two  Approach as follows :
If your String is InputString = "sj'ase'aa'"
First Approach
===========
Use String Method
string.escapeSingleQuotes(InputString);
output would be sj\'ase\'aa\'
Second Approach:
============

if(InputString.contains('\'')){
                       InputStringInputString.replaceAll('\'', '\\\\\'');
                                   
}

But Second Approach is limited up to only single quote but when you use back slash you can not use this approach.
so go to first one.