Generic way to Escape Quotes in Javascript Variable - javascript

I have a form where users can enter any HTML.
var title = "Cool Check This"
As you can see, the variable is having " but it can be also '. It causes an error if there is ". What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?

var title="Cool Check This"
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use addslashes() prior to inserting into JavaScript.
Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert <script>) can allow to do various dangerous stuff, like stealing all cookies.

Related

Escaping characters to avoid XSS in Java

I need to escape characters to avoid XSS. I am using org.apache.commons.lang.StringEscapeUtils.escapeHtml(String str), which helps in the following way:
Raw input
" onmouseover=alert() src="
After escaping HTML becomes
" onmouseover=alert() src="
However, there are cases in which the reflected input is trapped in single quotes, such as:
test'];}alert();if(true){//
In that particular case, escaping HTML does not have any effect. However, org.apache.commons.lang.StringEscapeUtils also has a method called escapeJavascript(String str), which would convert the input into:
test\'];}alert();if(true){\/\/
The question here is, would you sanitize your input by escaping HTML first and then Javascript? The other would be to replace the single quote character with \' manually.
Any help will be greatly appreciated!
As #gabor-lengyel mentioned I should be able to escape a single quote with an html encoder.
The problem I had is that I was using org.apache.commons.lang.stringescapeutils.escapeHtml and it is not capable of escaping single quotes with the corresponding HTML entity. I am now using org.springframework.web.util.HtmlUtils.htmlEscape, which is capable of dealing with both double and single quotes.
Thank you #gabor-lengyel again for your help!

How do I properly escape double-quotes when sending HTML from Applescript into Javascript?

I am working on an Applescript script which executes some Javascript to add some HTML to a webpage I am viewing on my local machine. Applescript is reading the HTML file into a string and automatically escapes all the double quotes in the HTML like this: \"
But Javascript doesn't like the string with all the escaped double-quotes in it:
set programHTML to "\"Hi kid!\"" --This works!
set programHTML to "\"Hi \"kid!\"" --This doesn't!
I feel like I must be missing something very basic here. I scanned and skimmed many posts but have not seen anything addressing this specific problem.
[Adding this after what would have been a helpful comment had I been a bit more explicit]:
Nothing with more than the quotes on the end works when it gets to Javascript. This does not work:
set programHTML to "\"Howdy, \"kid!\", is your \"Mom\" home?\""
I should perhaps mention that this string is going into a line which looks something like this:
execute tab 1 of front window javascript "codeDIV.innerHTML = " & programHTML & ";"
Double Quotes must always be used in pair. that's why your second method does not works.
set programHTML to "\"Hi kid!\"" --This works!
-- Because it results in "Hi kid" - 2 double quotes
set programHTML to "\"Hi \"kid!\"" --This doesn't!
Because it results in "Hi "kid!" - 3 double quotes
Change the outer quotes to single quotes so they don't interfere with the inner double quotes. If you do this, you don't need to worry about escaping the double quotes at all.
//using the single quote in the beginning and end
console.log('"Howdy, "kid!", is your "mom" home?"');
reads as "Howdy, "kid!", is your "mom" home?"

escape Hebrew double quote on both php and javascript

I'm working on multi-language site based on php.
For supporting multi-language, I'm using localizing file like below.
[localize.en-US.php]
$lang_code = "en-US";
$is_rtl = false;
.
.
.
define("WORD_EMAIL", "e-mail");
define("WORD_NAME", "name");
.
.
.
Defined words used by two way like below.
[HTML]
<?=WORD_EMAIL?> : <input type="text" name="email"/>
<?=WORD_NAME?> : <input type="text" name="name"/>
[Javascript]
if(frm.email.value==="") {
alert("<?=WORD_EMAIL?> required.");
return false;
}
The problem occured when I'd working on Hebrew.
The word "e-mail" of Hebrew tanslation has a double quote in it.
I tried to escaping double quote.
To escape double quote,
PHP need one backslash, and javascript need one more and one another for backslash.
So I added 3 backslashes before double quote.
it shows propery on javascript alert. but on HTML backslash(for javascript) appears..
Yes, I Know using single quote can solve this simply.
But it occurs an exception among localize files(some French word uses single quote).
Can anyone help about this? Any clues welcome.
You always need to encode or escape values for the context you're embedding them in. When putting anything into HTML, you need to HTML-encode it unless you accidentally want the values interpreted as HTML. When putting anything into Javascript source code, you need to escape it properly there, for which JSON-encoding happens to be the right technique:
<?= htmlspecialchars(WORD_EMAIL, ENT_COMPAT, 'UTF-8'); ?> : <input type="text" name="email"/>
alert(<?= json_encode(WORD_EMAIL); ?> + " required.");
Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
I would argue that your i18n approach of pretty flawed though; "אִימֵיְיל required"* seems like a very insufficient localisation. You will want to look into proper tools like gettext and implementations/analogues of it for Javascript.
* Google translation, I don't speak Hebrew…

Title Tag With Quotes & Apostrophe ( " & ' ) For Insertion In DB

I've been searching for a solution to be able to have the following:
a
so the tooltip shows up as: what's the big "DEAL" about "double quotes" & 'single' ones
So the user inputs their text in a dialog box and I'm using js to parse the text, put it in the wysiwyg (tinymce) and then send to db.
Here's what I've tried:
encodeURIComponent gives me:
what's%20the%20big%20%22DEAL%22%20about%20%22double%20quotes%22%20%26%20'single'%20ones
this doesn't solve it because when I take the data out of mysql and dump it back on the page I'm back to the original because I use url decode on the whole text (this I cannot change).
Tried escaping the quotes with regex like:
title.replace(/'/g, "\\'");
title.replace(/"/g, '\\"');
This worked on 'single' quotes but not double
What I get back is title="what\'s the big \" (note I'm using a prepared statement in php to insert this into the db)
I've researched escaping strings and certain characters in js or encoding them so for example " becomes " but all I get stuff that requires you to build your own functions. Is this the case?
My questions is this:
Am I missing something? Is there a more elegant solution to this? How would you recommend I do it? Where in the process should this be done?
I've seen this (How to escape double quotes in title attribute) but this doesn't explain how to create a robust solution for handling constantly changing user content (and title attribute).
Thank you all.

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

Categories