Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to escape single and double quotes with backslash

Tags:

jquery

regex

I want to escape single and double quotes with a backslash in one line rather than two.

Example for single quote:

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

Is there a way to do this at the same time for double quotes included?

Sniffer Answered this very well below, and I ended up escaping all characters we needed as follows:

str = str.replace(/(['"&:;])/g, "\\$1");

Thanks again Sniffer for the quick response!

like image 583
no1uknow Avatar asked Aug 28 '13 15:08

no1uknow


1 Answers

Try this:

str = str.replace(/(['"])/g, "\\$1");
like image 151
Ibrahim Najjar Avatar answered Sep 28 '22 16:09

Ibrahim Najjar