Skip to content
Amal Hashim
All posts
Snippet

JavaScript - Escape quotes

Escape single and double quotes in a string before an AJAX post, using a simple replace instead of encoding everything.

1 min read#JavaScript#jQuery

When you send data in an AJAX post, you may need to escape the quote characters. A JavaScript encoding function escapes the whole string. If you only want the quotes, replace is simpler.

js
data.replace(/(['"])/g, "\\$1")

Example

js
var data = 'He said "hello" and it\'s fine';
var escaped = data.replace(/(['"])/g, "\\$1");
// He said \"hello\" and it\'s fine