Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add slashes to a string in Javascript?

Just a string. Add \' to it every time there is a single quote.

like image 998
TIMEX Avatar asked Feb 03 '10 21:02

TIMEX


People also ask

How do you put a slash in a string?

The backslash ( "\" ) character is a special escape character used to indicate other special characters such as new lines ( \n ), tabs ( \t ), or quotation marks ( \" ). If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: "\\Tasks" or @"\Tasks" .


2 Answers

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'"); 
like image 112
Kobi Avatar answered Sep 20 '22 14:09

Kobi


Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

function addslashes(string) {     return string.replace(/\\/g, '\\\\').         replace(/\u0008/g, '\\b').         replace(/\t/g, '\\t').         replace(/\n/g, '\\n').         replace(/\f/g, '\\f').         replace(/\r/g, '\\r').         replace(/'/g, '\\\'').         replace(/"/g, '\\"'); } 
like image 37
Somnath Muluk Avatar answered Sep 17 '22 14:09

Somnath Muluk