Escaping string using JavaScript before populating form input - javascript

I have this code where I grab an attribute value and load it into a form, the headline line can look something like:
Welcome to America's best valued whatever
But when using this escape function, the string is cut off at the apostrophe,
var headline = escape($(this).attr("data-headline"));
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(headline);
I've also tried using the solutions here: HtmlSpecialChars equivalent in Javascript? with no luck.
How can I populate my input and keep apostrophe's/quotes?

Just use
$(this).find('input[name="headline"]').val(this.dataset.headline);
No need for any escaping.
However, notice that escape does not cut off apostrophes, it replaces them with %27. If your current code does not work with apostrophes in the headline, make sure that the markup containing the data-headline attribute is properly escaped by whatever tool is creating it.

var headline = $(this).attr("data-headline").replace(/'/g, '%27');
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(unescape(headline));
If browser compatibility is important, dataset is only available IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#Browser_compatibility

Related

display double escaped special characters - change " to " using Javascript or Jquery

I have a page developed by someone who is retiring. The page is programmed in ASP, and pulls info from a database we maintain. All special characters are double escaped, (i.e. " and &) so the browser is rendering as " and &.
I would like to switch the behavior to properly display " or & respectively.
The data is loaded into a table, and is wrapped in only in td /td
The simplest method for me would be javascript/jquery, but I cannot get it to work.
I have tried a few methods that i have found here on SO such as:
$('td').innerText.each(function() {
var text = $(this).text();
$(this).text(text.replace('&', '&'));
$(this).text(text.replace('"', '"'));
});
I haven't had luck so far. Any ideas?
Have you tried unescape() method in Javascript?

unescape in javascript not working when %26 ( & sign) is in value

I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.

JavaScript string declarations from dynamic data with unescaped quotation marks

I am writing JavaScript templates for a content management system where users fill out text input fields that are passed to my templates.
My problem is the quotation marks in the input fields are not escaped before they are passed to my template, so I have no way of knowing if they will contain single or double quotes, or even both. Whichever way I try to handle the data my code ends up breaking because the quotes terminate the string declaration. I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Is there any way to safely handle the data in JavaScript without it breaking a string variable declaration?
Edit: I'm posting code example;
CMS Text Input Field value is: Who'll win our "Big Contest"?
Text Input Field placeholder macro is [%TextInput%]
I'm building an HTML template for this input, using just JS/HTML/CSS
<script>
(function(){
var textInputStr = "[%TextInput%]";
})();
</script>
This will break the string declaration if the value of TextInput contains a single quote, and vice versa.
This is an awesome question, and one that deserves an answer. Strings in JS don't have a custom delimiter, like in most other modern languages, so you can get really stuck. But one solution is to build a script tag with the placeholder inside it, then find the innerHTML of that tag and grab the string back into a variable. eg
<script id="parseMe" type="text/template">
[%TextInput%]
</script>
then use
var yourString = document.getElementById("parseMe").innerHTML
Now you can manipulate the string as you please.
HTH!
I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Well, you will have to make it a valid string literal before you could run JavaScript functions on it. There's no other way (unless you count an ajax request to the template script to get a string representation of it).
The input fields are not escaped before they are passed to my template
Then fix that. There's nothing you can do about it in JavaScript.

JavaScript replace() one html entity with another

I want to get some textarea text and replace all bullet point html entities • with ·.
The usual approach str.replace(/•/g,"·"); doesn't work.
Any advice would be appreciated.
When you're getting the text value back from the textarea, it has already been converted to its actual character. To do a string replacement on that string, either
convert all characters to their html entity counterparts, then proceed with what you're doing or
use the character in the regex directly.
Here's an example of the second approach.
var newText = oldText.replace(/•/g, "");
You can fiddle with an example here.
If you want to go with the first approach, see this question and its answers for ways to convert characters in a piece of text to their corresponding html entities.
If you want to do this without jQuery:
var myTextarea = document.getElementById('id_of_your_textarea');
myTextarea.value = myTextarea.value.replace(/•/g, '·');
jQuery:
$("#myTextarea").val( $("#myTextarea").val().replace(/•/g, '·') );
.val() will get the value from an input element, .val('str') will set a value.

jQuery URI encode (char &) .html() attribute value

I've read a lot of the HTML encoding post for the last day to solve this. I just managed to locate it.
Basicly I have set an attribute on an embed tag with jQuery. It all works fine in the browser.
No I want to read the HTML itself to add the result as a value for an input field to let the user copy & past it.
The PROBLEM is that the .html() function (also plain JS .innerHTML) converts the '&' char into '& amp;' (without the space). Using differen html encoder functions doesnt make a difference. I need the '&' char in the embed code.
Here is the code:
HTML:
<div id="preview_small">
<object><embed src="main.swf?XY=xyz&YXX=xyzz"></embed>
</object></div>
jQuery:
$("#preview_small object").clone().html();
returns
... src=main.swf?XY=xyz&YXX=xyzz ...
When I use:
$("#preview_small object").clone().children("embed").attr("src");
returns
main.swf?XY=xyz&YXX=xyzz
Any ideas how I can get the '&' char direct, without using regex after I got the string with .html()
I need the & char in the embed code.
No you don't. This:
<embed src="xyz&YXX=xyz"></embed>
is invalid HTML. It'll work in browsers since they try to fix up mistakes like this, but only as long as the string YXX doesn't happen to match an HTML entity name. You don't want to rely on that.
This:
<embed src="xyz&YXX=xyz"></embed>
is correct, works everywhere, and is the version you should be telling your users to copy and paste.
attr("src") returns xyz&YXX=xyz
Yes, that's the underlying value of that attribute. Attribute values and text content can contain almost any character directly. It's only the HTML serialisation of them where they have to be encoded:
<div title="a<b"&c>d">
$('div').attr('title') -> a<b"&c>d
I want to read the HTML itself to add the result as a value for an input field
<textarea id="foo"></textarea>
$('#foo').val($('#preview_small object').html());
However note that the serialised output of innerHTML/html() is not in any particular fixed dialect of HTML, and in particular IE may give you code that, though generally understandable by browsers, is also not technically valid:
$('#somediv').html('<div title="a/b"></div>');
$('#somediv').html() -> '<DIV title=a/b></DIV>' - missing quotes
So if you know the particular format of HTML you want to present to the user, you may be better off generating it yourself:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
var src= 'XY=xyz&YXX=xyzz';
$('#foo').val('<embed src="'+encodeHTML(src)+'"><\/embed>');
(The \/ in the close tag is just so that doesn't get mistaken as the end of a <script> block, in case you're in one.)

Categories