I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:
function testEscape() {     var strResult = "";     var strInputString = "fsdsd'4565sd";      // Here, the string needs to be escaped for single quotes for the eval      // to work as is. The following does NOT work! Help!     strInputString.replace(/'/g, "''");      var strTest = "strResult = '" + strInputString + "';";     eval(strTest);     alert(strResult); }   And I want to alert it, saying: fsdsd'4565sd.
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!
Strings in JavaScript are contained within a pair of either single quotation marks '' or double quotation marks "". Both quotes represent Strings but be sure to choose one and STICK WITH IT. If you start with a single quote, you need to end with a single quote.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...   It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'"); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With