I am creating a bookmarklet and I have to avoid using double quotes ( " ) because I have to include the bookmarklet inside a HTML page and it's inside a string that uses double quotes:
<a href="javascript:...">
In some places I have to use the code replace(/".*/, '');
In sed, I can escape double quotes using \x22 (22 is the ASCII hex code for double quotes)
Is it possible to do something similar in JavaScript like replace(/\x22.*/, '');?
You can use the other syntax for making a RegExp and use String.fromCharCode
Here's an example:
'"hello"'.replace(new RegExp(String.fromCharCode(34), 'g'), '-quotes-')
-->
'-quotes-hello-quotes-'
The same way you would use quotes in any HTML attribute's value.
example
<img src="..." alt="A picture of Bob "e;Wild Man" Johnson">
so for you
<a href="javascript:replace(/".*/, '');">
Related
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!
I want a javascript alert that reads, "It's "Hammer" time!"
What is the best code to write this?
Although you could use a string with ' and escape the ', or a string with " and escape the "s, it would be better to use a template literal, which doesn't require escaping of quotes because its delimiter is the backtick:
alert(`"It's "Hammer" time!"`);
For displaying single or double quotes, you can write your code like this alert("\"It's \"Hammer\" time!\"")
You need to escape it using \
For example:
alert("Something \"here\"!!");
Escape the "s other than the ones from the begining and ending..
alert("\"It's \"Hammer\" time!\"")
How to display double quotes in JavaScript
Or use string interpolation, where you can have both without escaping.
alert(`Hello, I'm "nobody"!`);
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 ' 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 '
"<img src='something' onmouseover='change('ex1')' />";
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...
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()).
I have a MVC view in which I have to pass a string variable to JavaScript, but that string variable has single quotes in it ('). I am trying to do something like this
<a onclick="JavaScript:AddressHandler.ProcessAddress('<%= homeAddress %>');"
class="button-link">change</a>
homeAddress has single quotes which I have to workaround somehow so that I can pass the complete value of it to the JavaScript.
You can use Ajax helper: Ajax.JavaScriptStringEncode(string strToEncode)
To escape a string to be a Javascript string literal, you replace backslash with double backslashes, and the string delimiter with a backslash and the delimiter:
<a onclick="AddressHandler.ProcessAddress('<%= homeAddress.Replace(#"\", #"\\").Replace("'", #"\'") %>');" class="button-link">change</a>
Note: The javascript: protocol is used when you put script in an URL, not as an event handler.
Edit:
If the script also contains characters that need HTML encoding, that should be done after escaping the Javascript string:
<a onclick="<%= Html.Encode("AddressHandler.ProcessAddress('" + homeAddress.Replace(#"\", #"\\").Replace("'", #"\'") +"');") %>" class="button-link">change</a>
So, if you don't know what the string contains, to be safe you need to first escape the string literal, then HTML encode the code so that it can be put in the attribute of the HTML tag.
You can write a method that escapes all single quotes (and other characters if needed) with a backslash so it is not misunderstood by javascript.
You'll want to encode homeAddress as a URL. MVC has a built in helper to do this: UrlHelper.Encode(string url) - it should replace a single quote with %27
I don't have time to test it, but look at HtmlHelper.Encode(string s). It might handle the escaping for you.