The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Answer from Nikita Tkachenko on Stack OverflowThe thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='something' onmouseover='change(' ex1')' />
In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.
The truth is, HTML does not use \ for an escape character. But it does recognise " and ' as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
The answer here is very simple:
You're already containing it in double quotes, so there's no need to escape it with \.
If you want to escape single quotes in a single quote string:
var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
// ^ ^ same types, hence we need to escape it with a backslash
or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:
var string = 'this isn\\\'t a double quoted string';
// vvvv
// \ ' (the escaped characters)
However, if you contain the string with a different quote type, you don't need to escape:
var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
// ^ ^ different types, hence we don't need escaping
I need help with escaping literal quotes
Escaping both single and double quotes
Single quote escape in JavaScript function parameters - Stack Overflow
html - How to escape all single and double quotes in JavaScript - Stack Overflow
Videos
Hey,
I'm creating an object which contains user-typed content and the very same object will be printed / embeded somewhere else after. The tricky thing is :
- The object uses "xxx" for strings
- The place where it will be embeded as a text uses '{"mykey" : "myobject"}'
The object's creation is done using js ; the embed is in a bash environment. These are two separate scripts. So, basically, I want to escape all quotes and single quotes but also avoid escaping a user-typed quote like in this case \', which would output \\' and unescape the quote by escaping the escape itself. When I build my string, it seems that the quotes are successfully replaced with escaped ones. But then when I return the string, is seems that the escape is taken in account so the escapes disappears. What I'm trying to explain is that apparently when I return the escaped string, JS uses it to return the unescaped version.
How can I escape quotes and keep the string escaped for later use ? thanks
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.
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);"
The correct way to handle this is to escape the HTML in your JSP file, and also bind the event unobtrusively. The values from the database can be put in data-* attributes. For example, your HTML would be something like the following. Include this at the top of your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Using <c:out /> will encode special characters for correctly outputting into HTML, such as ', ", and & (among others).
And then change your HTML to be:
<input type="button" id="btnSubmit" value="Edit"
data-question-id="<c:out value="${QuestionId}" />"
data-question="<c:out value="${Question}" />"
data-question-data-type="<c:out value="${QuestionDataType}" />"
data-audio-path="<c:out value="${AudioPath}" />"
data-security-question-type="<c:out value="${securityQuestionType}" />" />
And your JavaScript:
window.onload = function () {
document.getElementById("btnSubmit").onclick = function () {
var questionId = this.getAttribute("data-question-id"),
question = this.getAttribute("data-question"),
questionDataType = this.getAttribute("data-question-type"),
audioPath = this.getAttribute("data-audio-path"),
securityQuestionType = this.getAttribute("data-security-question-type");
editSeqQuestion(questionId, question, questionDataType, audioPath, securityQuestionType);
};
};
Of course, it is "better" to use addEventListener, instead of setting onload and onclick. So you might use this:
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
}
}
and then bind events like:
addEvent(window, "load", function () {
addEvent(document.getElementById("btnSubmit"), "click", function () {
// The code from above
});
});
Reference:
addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Yes, you have a few options. Two are the most obvious:
- Tackle it server side and have your value come into your page from your JSP already string replaced with an html entity ' being the most logical (then you don't worry about your quote notation.
- Abstract it one way or the other into a js variable. Passing a js variable into a function obviates the need to escape the quotes (at least while passing it).
The first option is the least amount of work in some ways. Depending on how dynamic this is supposed to be, you might opt for the second option. In that case, I would suggest the jsp building a nice object or array for you in js which you can then reference (I am guessing you have more than one question set). Have the jsp set a unique id on each element and then have the onclick reference the array by the same id notation to use the object/array stored values as necessary. Go one step farther and bind your function to the elements and follow unobtrusive code methods.
In the short run, your page might end up looking something like this:
<script>
aQs = [
{v: 72, q: 'What is child's name', t: 'AN', s: 'nick.wav', title: 'Sec'},
{v: 23, q: 'What city', t: 'AN', s: 'city.wav', title: 'Sec'}
];
function edQ(qId) {
dosomething(aQs[qId]);
}
</script>
<input type="button" id="btn_0" Value="Edit" onclick="edQ(this.id.split('_')[1])" />
<input type="button" id="btn_1" Value="Edit" onclick="edQ(this.id.split('_')[1])" />
In either case, I think the easiest/safest thing to do to generally handle the ' is to replace it server side with an html entity.
You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.
Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, ".
" would work in this particular case, as suggested before me, because of the HTML context.
However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
' becomes \x27
" becomes \x22
So your onclick would become:DoEdit('Preliminary Assessment \x22Mini\x22');
This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert() is an easy test method for this).
I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.