Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quotes in JavaScript string for JavaScript evaluation

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.

like image 273
Florian Mertens Avatar asked Feb 26 '13 11:02

Florian Mertens


People also ask

How do you escape quotes in JavaScript?

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!

Can you use single quotes for strings in JavaScript?

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.

Should I use double quotes or single quotes in JavaScript?

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!


1 Answers

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, "\\'"); 
like image 51
Nikita Tkachenko Avatar answered Sep 30 '22 18:09

Nikita Tkachenko