Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single quote escape in JavaScript function parameters

I need to escape single quotes in JavaScript function parameters to avoid this:

onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5  ',this);" 

But I need to escape them inside a function call since I do not know the values that will be passed (db variables I can't escape from the database).

Is there a function that allows me to do something like the following?

onclick="Javascript:function(escape(param1), escape(param2), escape(param3));" 
like image 281
Daniele Di Punzio Avatar asked Jan 05 '12 14:01

Daniele Di Punzio


People also ask

How do you escape a single quote in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

What is the escape sequence for a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

Can you use single quotes in JavaScript?

In JavaScript, single (' ') and double (“ ”) quotes are frequently used for creating a string literal. Generally, there is no difference between using double or single quotes, as both of them represent a string in the end.


Video Answer


2 Answers

 JSON.stringify(plainTextStr).replace(/&/, "&").replace(/"/g, """) 

will produce a string you can safely embed in a quoted attribute and which will have the same meaning when seen by the JavaScript interpreter.

The only caveat is that some Unicode newlines (U+2028 and U+2029) need to be escaped before being embedded in JavaScript string literals, but JSON only requires that \r and \n be escaped.

like image 135
Mike Samuel Avatar answered Oct 04 '22 13:10

Mike Samuel


Escape the apostrophe with a backslash:

onclick="INSERT_PRODUCT('188267','WILL AND GRACE ','32311','L\'ANNIVERSARIO DI NOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);" 
like image 33
Iain M Norman Avatar answered Oct 04 '22 14:10

Iain M Norman