Cross-language string escaping - javascript

I have a string in C# that contains an error message. This message could contain single quotes or double quotes or both, but I am free to manipulate the string however I need (as well as the HTML/Javascript).
For example, the following messages could be displayed (content isn't important, just the fact they could contain single or double quotes):
The following error has occurred: "You dun goofed."
The specified path isn't valid.
The following error has occurred: "I'm a goof"
This string is inserted into HTML as an alert inside of an onClick handler. That sounds complicated so let me show what I mean:
<a onClick="alert('myContentGoesHere')">View Error</a>
I'm able to get the single quotes to display by replacing ' with \' in C#. However, my attempts to similarly escape " has resulted in an odd number of backslashes which terminates the onClick attribute and causes invalid HTML.
So far I have tried to replace " with:
\"
\\"
"
\"
No dice. I feel like I might be approaching this from the wrong angle so if you have a solution which goes beyond a string replace, I'm all ears. Thanks for any help you can offer.

To make the value work as a string literal in JavaScript you need to escape the string delimiter and backslashes. Then you need to HTML encode the JavaScript so that it works as a value in the HTML attribute.
Example:
string code =
"<a onClick=\"" +
HttpUtility.HtmlEncode(
"alert('" +
myContentGoesHere.Replace("'", "\\'").Replace("\\", "\\\\") +
"');"
) +
"\">View Error</a>";
If the string can contain control characters, you would need to replace them too. Add the ones that you need from:
.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\b", "\\b")
.Replace("\t", "\\t")
.Replace("\v", "\\v")
.Replace("\f", "\\f")

Related

Replace line end with line end + double quote javascript

I started something that appeared pretty easy, but it worked out differently.
I have this string, read from a file:
"columns:[
{
allowNull:false,
I want to replace the newline with a newline and a double-quote.
so I do:
text = text.replace(/\r?\n/g, '\n"')
somehow, the output is this:
"columns:[
\"{
\"allowNull:false,
I'm completely puzzled as to where the extra '\' is coming from. If I use a single-quote, or another character, it works just fine
What is going on here?
Within here
text = text.replace(/\r?\n/g, '\n"')
you replace with \n" instead of \n. As #vlaz indicates correctly in the comments, text.replace does not escape " to \". But the print function does.
Anyway, there's a " which may be not intended.

How to replace this strange quote-looking symbol: “, with a proper double quote: "

I have a textarea that is used as the body of an email sent out by a Java class.
A user has reported that after copying text from Apple's Keynote, and sending an email, characters that are supposed to be double quotes, show as '?'.
On further inspection it seems the user has used this symbol: “ , rather than the typical ' " ' .
I have been trying to replace this symbol in javascript (without success) by using:
str.replace("“", '"')
The code you've posted does work:
> "“".replace("“", '"')
"""
However, this won't solve the issue, as you'll get similar results for other unicode characters.
This is an issue that will need to be fixed on the back-end, as that's most likely where the Unicode is being handled incorrectly.

How do I get the single quotes to remain in the variable?

This is a combination of classic ASP and Javascript, we are trying to insert a single quote around each itemno but it is not working.
It is ending up looking like this: 10234,12343, instead of '10234','12343',
(The trailing comma I strip later)...
What can be done differently to keep the ItemNo's single quoted?
var Prefix_JS_Item = [<%For intA = 1 to intCount%><%="'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "',"%><%Next%>];
document.write(Prefix_JS_Item);
There have been two attempts so far but try this:-
var Prefix_JS_Item = [<%For intA = 1 to intCount%><%="""'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "'"","%><%Next%>];
document.write(Prefix_JS_Item);
Javascript supports both " and ' to enclose a string literal. So to include a ' in a literal you can use " to enclose the literal. Now in VB to include a " in string literal you double them to "".
BTW, don't "quote" me (sorry) but in javascript I think you can get away with the trailing comma.
The script is doing what you want. The way you verify is what is wrong.
After ASP executes you will have '10234','12343' inside the JavaScript. To see it go to "view source code" (CTRL + U) in your browser.
Then you write it to the document. To JavaScript '10234' the quotes are delimiters for a string. Therefore it will only write what is inside them.
If you still want to have quotes even when writing it to the document then:
... <%="""'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & """," %>
document.write(Prefix_JS_Item);
Which in javascript will look like: "'10234'","'12343'"
EDIT: To scape quotes in ASP you use another quote.
you have to escape the single quote
...<%="\'" & trim(Mid(cartobj(intA).Item("ItemNo"),4)) & "\',"%><%Next%>];

JQuery escape apostrophes and double apostrophes?

I want to use JQ to print to a div on my page. The string I want to print with contains HTML including apostrophes and double apostrophes.
Is there a plugin or function to escape this so that the string doesnt break the js variable? There may be the case that I can't escape all of the apostrophes and double apostrophes in the incoming data using a backslash, so I'm looking for a function that can do it.
EG;
var replacement = 'This content has an apostrophe ' and a double apostrophe "';
$("#overwrite").text(replacement);
TIA
If you wanted to type out a string that is assigned to a variable like in your example above, then just escape it yourself.
For example, if I know my data will have apostrophes, then I wrap it in quotes (what you are calling double apostrophes) and use the HTML shortcut for quotes " or you can use a backslash to escape the quote \". Either way works. So your example above would become:
var replacement = "This content has an apostrophe ' and a double apostrophe "";
If the user is typing in the string or you are getting data from a feed, then it would be best to use the javascript replace function to make sure the quotes are escaped, like this:
var text = $("input").val().replace(/\"/g,""");
There is no need to escape incoming data, as it is already a string.
The only reason you need to escape apostrophes and double apostrophes in JavaScript source is due to the fact the JavaScript engine has to determine where the string starts and ends.
For instance, assuming you have a div#source containing the text "Hi there, what's up!", it is perfectly safe to do $("#overwrite").text($("#source").text()).

How to get a Clean String in Javascript?

i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.

Categories