javascript array as a list of strings (preserving quotes)


I've got an array of strings. When I use .toString() to output it the quotes are not preserved. This makes it hard to build the mysql query using an "in". Consider the following:

SELECT * FROM Table WHERE column IN ('item1','item2','item3','item4')

toString is returning: IN (item1,item2,item3,item4)

There must be a simple fix I am overlooking here.

12/13/2011 6:21:20 AM

Accepted Answer

The quotes aren't preserved because they're not actually part of the string value, they're just necessary to indicate string literals in your code.

So, don't use toString(). Instead, one way to do it is as follows:

var arr = ['item1','item2','item3','item4'];

var quotedAndCommaSeparated = "'" + arr.join("','") + "'";

// quotedAndCommaSeparated === "'item1','item2','item3','item4'"

The Array.join() method returns a string that is all of the array elements concatenated into a single string with an (optional) separator between each item. So if you specify a separator that includes the quotation marks and commas you just have to manually append a starting and ending quote for the first and last item (respectively).

(And please tell me you're not using client-side JavaScript to form your SQL.)

EDIT: to allow for an empty array, include a default value for the resulting string, otherwise (as pointed out by missingno) the string would be "''":

var newString = arr.length === 0 ? "" : "'" + arr.join("','") + "'";
// default for empty array here ---^^

(Might be more appropriate to have an if (arr.length===0) to take some other action rather than running the SELECT statement.)

12/13/2011 1:32:13 PM

The simple fix is adding the quotes yourself

for(var i=0; i<items.length; i++){
    items[i] = "'" + items[i] + "'";

var list_with_quotes = items.join(",");

Do note that I completely ignore SQL injection issues here.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow