Encoding data in an attribute using encodeURIComponent() vs using JSON.stringify()

When attempting to use an array as a data attribute, many StackOverflow answers recommend using JSON.stringify();

If I have this array: ['something', 'some\'thing', 'some"thing'], it will be parsed like "["something","some'thing","some\"thing"]" and won't fit in either data-*='' or data-*="" because of the quotation marks.

Is encodeURIComponent() the correct solution for encoding arrays like this? Why hasn't this issue been noticed in other StackOverflow answers?

Answer №1

The argument that JSON.stringify may not always be secure in HTML attributes when the text is part of the HTML markup itself holds merit. However, there are no escaping concerns if utilizing access methods like .data or .attr to set the value as they do not directly alter raw HTML content.

While using encodeURIComponent could technically solve the issue by escaping problematic characters, it leads to unsightly values/markup and requires manual decoding with decodeURIComponent when consuming the data - not ideal!

Instead of directly inserting data into HTML, encode the value for HTML and use the encoded result as the attribute value. Most server-side languages offer a function for this purpose, though JavaScript does not provide an equivalent natively.

If attribute values are enclosed in quotes, certain characters must be replaced with their corresponding HTML entities:

  • & - &, escape-the-escape, should be applied first
  • " - ", for double-quoted attributes
  • ' - ', for single-quoted attributes
  • Optional (required for XML): < and >

This approach relies on parsing the HTML markup and automatically decoding HTML entities within it, ensuring that the actual (non-encoded) data is stored as the value of the data attribute in the DOM.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to format the POST body using httr in R

I've been attempting to update a contact property value in hubspot but have come across some challenges. For more information, you can refer to the documentation: The data I'm working with is stored in JSON format within a series of data frames ...

Having difficulty altering the color of my 3D model using three.js

I'm currently facing an issue with my 3D gltf model of a building on a Mapbox Map. Despite trying to change the color using MeshPhongMaterial or other variations, it seems that the color remains unaltered. Everything else appears to be functioning co ...

Is it possible to erase the text area in MarkItUp?

I'm currently facing an issue with clearing my MarkItUp editor. I've successfully managed to insert text using the $.markItUp function, but I'm struggling to clear the text box afterward. I attempted to use replaceWith: "", however, I encoun ...

What is causing JS to malfunction and preventing App Scripts from running `doGet()` when using either `e` or `event` as parameters?

Following a Basic Web App video last night, I meticulously followed every step until the very end where things started to go wrong. Today, I decided to start from scratch and recreate it all. Despite weeks of coding practice, I can't seem to figure ou ...

Using ajax to submit variables may not function properly

I have a set of data that has been processed using JavaScript and I am looking to save it to a database. I have been attempting to code something with AJAX, but so far, I have had no success... What I require: Two variables (id, name) need to be sent to a ...

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

Preserving objects/variables in non-volatile storage

SUMMARY Though I lack extensive programming experience, I am currently developing a hybrid mobile app with Cordova. The app will contain a substantial amount of static data which needs to be referenced periodically for basic operations. As the volume of o ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Dealing with XML parsing when there are multiple sibling elements with identical names

My task involves parsing an XML document and displaying the elements in a table format on the UI. Alternatively, I can work with JSON data if available. However, I am facing difficulty in extracting all elements from the XML due to multiple occurrences of ...

What causes the ng-class directive to be executed subsequent to my custom directives?

For the example I am referring to, please visit: http://plnkr.co/edit/oYvwHnAIvFb4rUqqwsz3?p=preview Hello, I am facing a situation where Angular seems to be compiling my code in a way that I do not fully understand. I have an outer directive that is iter ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

Persistently Undefined Angular Attribute

I have been trying to dynamically bind a CSS class using an AngularJS function. While the functionality is working properly, I keep encountering numerous errors in the browser console. Can anyone offer assistance with this issue? I have included my code an ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

Activating Unsplash API to initiate download

I am currently following the triggering guidelines found in the Unsplash documentation. The endpoint I am focusing on is: GET /photos/:id/download This is an example response for the photo: { "id": "LBI7cgq3pbM", "width": ...

What is the best way to format dates in jQuery AJAX requests?

Utilizing jquery to interact with a REST API in (ASP.net Web API). I've constructed a basic object and then utilized jquery to 'PUT' it on the server: var myObject = { name: 'just a name', createDate: new Date() } $.ajax({ ...

Is it true that the Spring MVC <input:form> does not support the use of the name attribute? This limitation could potentially pose challenges when utilizing javascript document.getElementsByName

Check out my Spring MVC JSP snippet below: <c:forEach var="trackRecord" varStatus = "number" items="${contractDetails.trackRecordEntries}" > <tr class="tafont"> <td class="varcar"><form:input readonly = "true" name = "install ...

Troubleshooting issues with the malfunctioning Bootstrap dropdown tab

My dropdown used to switch between panes for the selected item in the dropdown by clicking on it, but after updating to the new bootstrap version (4.0.0-beta.2), it no longer responds and shows a tab.js:155 Uncaught TypeError: Cannot read property 'no ...