Single quote escape in JavaScript function parameters

我是研究僧i 提交于 2020-01-26 09:44:06

问题


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));"

回答1:


 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.




回答2:


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);"



回答3:


It's maybe not totally clear from the question, but assuming that all you want is to send this to a PHP script for storing in a database, you of course would ideally utilize PHP's various methods such as stripslashes() -- but if you're really not trying to get too fancy, simply adding 1 slash in front of any single quote is enough to send a SQL query right into PHP from the client-side. It's not safe, but maybe not necessary either.

str.replace(/'/g, "\\'"); // escaping \ with \, so used 2x

does the trick., like for example in something like this:

var body = $('#body').val().replace(/'/g, "\\'");
myCustomSQLqueryFunction("UPDATE mytable SET `content`='"+ body +"';" );

MySQL will now store your body like you see it in the form field.




回答4:


This function worked for me (it removes and restores the quote again): Guessing that the data to be sent is the value of an input element,

var Url = encodeURIComponent($('#userInput').val().replace("'","\\'"));

Then get the original text again:

var originalText = decodeURIComponent(Url);



回答5:


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

its working for me.




回答6:


I prefer to use single quote for defining JavaScript strings. Then I escape my embedded double quotes as follows.

This is how I do it, basically str.replace(/[\""]/g, '\\"').

var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');

//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>


来源:https://stackoverflow.com/questions/8744315/single-quote-escape-in-javascript-function-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!