0

I am using phonegap for my mobile application . I need to generate queries dynamically and then execute the query;

qry += "('" + item1 + "','" + id + "','" + item2 + "','" + item3 + "'),";

item1,item2,item3 should be strings so that query happens successfully while executing.

the above bit of is fine for my use case in most of the cases . But i got an unexpected error now .

If the value from item1 is as 1'Feet or 10 ' Feet code breaks and execution fails .

How can i overcome this ?

user3383301
  • 1,891
  • 3
  • 21
  • 49

3 Answers3

1

Here is an ES2015 solution to show off template tags:

function esc(pieces, ...subs) {
    var result = pieces[0];
    for (var i = 0; i < subs.length; ++i) {
        // uses `.escape`, use other escaping function if you want.
        // for example with `/`
        result += escape(subs[i]) + pieces[i + 1];
    }
    return result;
}

Template tags give us custom logic for templating in the new ES2015 standard and are very useful for this thing.

var hello = "9'c"
console.log(esc`(${hello})`); // (9%27c)

function esc(pieces) {
    var result = pieces[0];
    var subs = [].slice.call(arguments, 1);
    for (var i = 0; i < subs.length; ++i) {
        result += escape(subs[i]) + pieces[i + 1];
    }
    return result;
}
var hello = "9'c";


document.body.innerHTML = esc`(${hello})`;
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

At last found answer , We need escape string in Sql rather than in jquery , replacing double single quotes instead of an single quote solves the problem .

item1.replace(/'/g, "''") ;

Escape Character in SQL Server

Community
  • 1
  • 1
user3383301
  • 1,891
  • 3
  • 21
  • 49
-2

[Edited the previous answer]

Try this,

<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script type="text/javascript">
   function fnEscapeQuotes(){
    var item1= "Ford's";
    var item2= "Dodges's";
    var item3= "Benz's";
    var id=100;
    var qry = "('" + item1 + "','" + id + "','" + item2 + "','" + item3 + "'),";
    alert(JSON.stringify(qry).slice(1, -1));
   }
  </script>
 </head>
 <body onload="fnEscapeQuotes();">
  
 </body>
</html>
David R
  • 14,711
  • 7
  • 54
  • 72