How do I escape a single quote ( ' ) in JavaScript? [duplicate] - javascript

This question already has answers here:
Why are inline event handler attributes a bad idea in modern semantic HTML?
(3 answers)
Single quote escape in JavaScript function parameters
(7 answers)
Closed 9 years ago.
UPDATE:
I want to give an updated answer to this question. First, let me state if you're attempting to accomplish what I have below, I recommend that you manage events by adding event listeners instead. I highly recommend that you utilize jQuery for your project and use their syntax to manage event listeners over using DOM.
QUESTION
Okay, I am basically doing this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\'ex1\')' />";
I don't want double quotes (") where I put the \'. I only want a single quote, so I am trying to not make it put a double when it is used. I am trying to reach this in the final outcome.
<img src="something" onmouseover="change('ex1')" />
Escaping isn't working for me.
My marked answer works fine, however, the cleaner (and more professional-looking way, IMO) is loganfsmyth's answer.

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 &apos; 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

You can escape a ' in JavaScript like \'

Since the values are actually inside of an HTML attribute, you should use &apos;
"<img src='something' onmouseover='change(&apos;ex1&apos;)' />";

document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";
OR
document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';
It should be working...

Related

How to set up a javascript variable with apostrophes and quotations marks (Can't escape it!)

I am currently working on a project where I don't have an access to their server side. All I can do is retrieve the blog data from their template editor, but it seems like there's no way to escape HTML using their template syntax. This is bad, but I need to assign the HTML in a javascript variable to create a Json data.
In Python, you'd use both apostrophes and quotation marks without escaping it by using three apostrophes as such:
example = '''
this '/ is great! ""Wahjhahaha
'''
Is there any equivalent way of this in Javascript? As I mentioned, I can't escape the HTML data.
"\" is the escape character in javascript.
var example = "This is a string with \' \" ";
console.log(example);
There are several approches depending on what you want to do.
You can use single quoute inside double quote.
You can use double quote inside single quote.
And if you want to use double quote inside double quote you have to use backslash (\) before the element. The same applies for single quote
console.log('This is double quote inside single quote "');
console.log("This is single quote inside double quote '");
console.log('This is single quote inside single quote \'');
console.log("This is double quote inside double quote \"");
console.log('\' " " \'');
console.log("' \" \" '");
EDIT
You need to use function replace()
var str = "Using single quotes ' ' sdsd 'sd 'dssd sdf' 'sdf'";
str = str.replace(/'/g, "\\'");
console.log(str);
Similarly you can do with double quotes.
Alternatively you can use backticks, but I would not recommend it (backticks in IE11)
console.log(`Here you can use both ' single and " double quotes without backslashes`);

Including JS lines in variable? [duplicate]

How can I include a double quote in a JavaScript string to be shown in the browser?
I am working on my JavaScript homework and I have to include double quotes in the middle of my list as shown below:
if (i == 0) {
error += "<li> this is not the name "....." </li>\n"
}
Use single quotes.
error += '<li> this is not the name "....." </li>\n';
Or escape the double quotes.
error += "<li> this is not the name \".....\" </li>\n";
Use single quotes as your string delimiters:
if (i == 0) {
error += '<li> this is not the name "....." </li>\n'
}
If you have single quotes in the string, delimit it with double quotes.
If you have double quotes in the string, delimit it with single quotes.
If you need to use both types in the string, escape whatever delimiter you have chosen by prefixing it with a \.
Consider to use the default entity
"
error += "<li> this is not the name “.....” </li>\n"
Or, if you use a variant of English where single quotation marks are the norm, as usual in British English,
error += "<li> this is not the name ‘.....’ </li>\n"
Using proper punctuation marks, you won’t encounter problems with the quoting conventions of JavaScript. Computer languages use ASCII quotes, human languages don’t.
Just make sure your document is properly encoded (both Windows-1252 and UTF-8 would do here) and the encoding is properly declared.

How do you use multiple quotes in javascript?

What do you do when you already have single and double quotes in a URL, but then you need to wrap that URL in quotes?
For example:
<script src="http://(some url text)xpath='//*[#id="node-1075"]/div/div[1]/div/div/p[2]'"></script>
The node ID is wrapped in quotes, if I put the URL alone in the address bar it works, but as soon as it gets wrapped in quotes it doesn't, I can't escape the quotes either or else it will fail, what do I do?
You should be able to replace the double quotes with: %22
And the single quotes with: %27
So your URL would be:
"http://(some url text)xpath=%27//*[#id=%22node-1075%22]/div/div[1]/div/div/p[2]%27"
Here is the complete list of ASCII Encoding http://www.w3schools.com/tags/ref_urlencode.asp
You need to escape them; usually you write (inside HTML files) double quotes first, then single quotes (the opposite in .js files, but that's my personal style); whenever you need the same in between you need to escape it.
Example:
document.getElementById("some").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
Notice that using the JavaScript escape character (\) isn't enough in an HTML context; you need to replace the double-quote with the proper XML entity representation, ".
Example:
Do It!
In your case, I would recommend to URL encode "the URL" though.

Cross-language string escaping

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

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()).

Categories