javascript array as a list of strings (preserving quotes)

前端 未结 5 801
刺人心
刺人心 2021-01-31 16:05

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 fol

5条回答
  •  时光取名叫无心
    2021-01-31 16:55

    Use Array.map to wrap each element with quotes:

    items.map(function(item) { return "'" + item + "'" }).join(',');
    

    The code gets simpler with ES6 features - arrow functions and template strings (implemented in node.js 4.0 and higher):

    items.map(i => `'${i}'`).join(',');
    

    You may also use whitelisting to prevent SQL injections:

    const validItems = new Set(['item1', 'item2', 'item3', 'item4']);
    
    items
       .filter(i => validItems.has(i))
       .map(i => `'${i}'`)
       .join(',')
    

提交回复
热议问题