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()).
Related
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`);
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.
the sample is like this:-
var encdata= escape('They're good at coding."Super". Its great!');
Now the error comes because it finds the closing apostrophe at they're instead at last.
It will work if i code the same as
var encdata= escape('They re good at coding."Super".Its great!');
Similarly if i use double quotes and give like
var encdata= escape("They're good at coding."Super".Its great!");
It will throw error at "super" but not at they're.
So, it should work when my text contains both double quotes and apostrophe.
And i can't wrap my text within as 'text' or "text".
So, i need an alternate solution for it
Escape the characters with \' or \";
var encdata = escape('They\'re good at coding."Super".Its great!');
var encdata = escape("They're good at coding.\"Super\".Its great!");
you need to use \" or \':
var encdata= escape("They're good at coding.\"Super\".Its great!");
or
var encdata= escape('They\'re good at coding."Super".Its great!');
you have to use a slash \ to escape the apostrophe inside the single quotes, or alternatively the open quotes inside the double quotes.
'They\'re good at coding."Super". Its great!'
"They're good at coding.\"Super\".Its great!"
This is true for almost every language ever. Adding a slash to characters lets it know that you want it to be a literal character instead of having a special meaning.
I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example
"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]
\ is an escape character. try \\
If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';
I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/
I am having problems when trying to use a rails variable within javascript code.
For example, I might define a link_to_remote, with parameter
:complete => "alert('my_var');"
If my_var = "I'm testing.", then the javascript code will break due to the single quote closing the code prematurely. If I try using escape_javascript(my_var) so that the quote gets turned into \', it doesn't seem to fix the problem.
I've noticed that when you try alert('I\'m testing'); there's a problem, but if you do alert('I\\'m testing'), it works. Since escape_javascript only turns ' into \', rather than \\', does somebody have a suggestion for how to handle this?
Thanks!
Eric
when you try alert('I\'m testing'); there's a problem
Backslash is also an escape in Ruby strings! So the string literal:
"alert('I\'m testing');"
means the string:
alert('I'm testing');
the backslash is gone already before JavaScript gets a look at it. When you are writing a JavaScript string literal inside a Ruby string literal you need to escape the escape, \\, to get a real \ that will then, in JavaScript, escape the apostrophe.
escape_javascript correctly generates the backslash for JavaScript, if a backslash was included in its input. But again, if you're writing a string literal, you have to escape the backslash to get a real backslash:
escape_javascript("\b") -> this is a backspace character!
escape_javascript("\\b") -> this is backslash-then-letter-b;
escaped for JavaScript literal to double-backslash-then-b.
So, this is fine:
"'"+escape_javascript(myvar)+"'"
alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.