I am looking for a JavaScript regex which will escape single quotes but it should not escape single quotes which are already escaped.
If there are an even number of backslashes, they only quote each other. Thus a character is quoted if it has an odd number of preceding backslashes. Since JS doesn't support lookbehind, you'll need to capture the leading non-backslash and include it in the replacement.
var escquote = /((^|[^\\])(\\\\)*)'/g
"a ' b \' c \\' d".replace(escquote, "$1\\'")
However, if this is for any sort of security purposes, it's the wrong approach for a number of reasons. Firstly, if you're doing this client side, it isn't secure. Second, quoting should be handled when data is sent to a subsystem using the methods provided by the subsystem. For example, if the data is going to a relational database, you should use prepared statements and parameterize the varying data. Prepared statement parameters aren't vulnerale to injection.