Function to escape quotes in JavaScript

elasticsearch, escaping, javascript, search

Solution

query_str = query_str.replace(/"/g, '\\\"');

..will result in; `"` to `\"`

OR

query_str = query_str.replace(/"/g, '\\\\\"');

..will result in; `"` to `\\"`, which will make a printed quotation still be escaped to `\"`.

This code;

var test = 'asdasd " asd a "';

console.log(test.replace(/"/g, '\\\"'));
console.log(test.replace(/"/g, '\\\\\"'));

..outputs;

asdasd \" asd a \"
asdasd \\" asd a \\"

You might adjust the replacement based on how your final interpreter reads the string and prints it out.

Problem

to start off, I don't do much JavaScript and am a complete newbie at it, now that's out of the way.. I've got a slight problem I'm trying to escape quotes from users inputs in my search app: ``` function getQString() { var query_str = 'q=' + $('input[name=q]').val().trim(); return query_str; } ``` This is done as a method within a gsp file, is there something equivalent to .escape() in JavaScript? This query is later sent to elastic search and gives me hell due to the quotes especially input like a"b.. I'm using ES 0.20.6

Original source