Transform a string expression into a JavaScript object (not JSON format)

There is an expression within a contenteditable div that looks like this:

{
    name : "Jeff",
    job : "rat whacker"
}

I am wondering how to convert this into a JS object?

If I extract the string from the div:

$("div").text();

...I would get this output:

"{\n    name: \"Jeff\",\n    job: \"rat whacker\"\n}"

Since this is not valid JSON, using JSON.parse won't work. How can I retrieve this as text and then assign it to a regular JSON object like this:

{
    name : "Jeff",
    job : "rat whacker"
}

Answer №1

It is crucial to never trust individuals when it comes to allowing arbitrary code execution on your site. To prevent abuse, ensure that user input is thoroughly validated before progressing to the next stage.

You can either extract the textContent from your div, convert it into valid JSON format, and then parse it using JSON.parse (which automatically detects parsing errors), or directly interpret the text as JavaScript while disregarding any potentially harmful elements like functions or execution operators. If you only need to accept basic input similar to what is being displayed, creating a simple and restricted JS parser may be a suitable solution with minimal effort required.

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

not capable of outputting findings in a sequential manner

I am encountering an issue where my result is not printing line by line, instead everything shows up on a single line. How can I resolve this problem? Here is the code snippet I have tried: <script> function know(){ var num = Number(doc ...

Find the total quantity of items meeting a specific criteria within a MongoDB database collection

I'm struggling to identify the issue in my query. My goal is to retrieve the count of "alerts" with the "resolved: false" field, so my query is : Alertes.find({resolved: false}).count(); Unfortunately, it's returning 0 even though I have one en ...

use two separate keys for grouping in JavaScript

My current approach involves using the reduce method to organize the data based on the Id of each query. var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descricao: "Creme", }, {Id: "545", valor: "2 ...

Ways to implement bootstrap Modal on a different HTML page

Does anyone know the best way to utilize the Bootstrap modal in a separate HTML page that is generated within the initial HTML page? ...

Encountering 500 error from server specifically when using preventDefault on form submission

I've been attempting to make a straightforward AJAX post on an ASP.NET MVC form without causing a page redirect, but I keep getting a 500 error from the server. When I remove preventDefault, everything works fine, except that the page changes and I se ...

"Troubleshooting: Why Won't insertAfter Function Work with

I have a p Element that I want to wrap inside a span tag. Then, I need to insert it after another p tag with the id output. Despite my attempts, the insertAfter function is not working as expected. $mytext = $("p#test").html(); $myspan = "<span styl ...

`Adjusting video frame on canvas`

When I capture video from a user's camera and display it in a 1:1 square, I encounter an issue when trying to draw the picture to a canvas. The image is not drawn in the same location on the canvas. How can I resolve this problem? To see a live examp ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...

Tips for identifying and logging out a dormant user from the server side using Angular 2 Meteor

I'm currently diving into Angular 2 Meteor and working on a project that requires logging out the user when they close their browser window. I also need them to be redirected to the login page when they reopen the app. After searching online, I could ...

Simplified JavaScript code for generating concealed input forms

Seeking assistance to enhance the form I designed, despite my limited knowledge in JavaScript programming. The objective is to develop a hotel search engine with the ability to specify the total number of rooms. Based on the selected number of rooms, addi ...

Unable to bring in a TypeScript library that was downloaded from a GitHub fork repository

Currently, I am working on developing a GitHub app using the probot library. However, I have encountered an obstacle as outlined in this particular issue. It seems that probot does not offer support for ESM modules, which are crucial for my app to function ...

NodeJS - session information lost after building ReactJavaScript application

I've created a NodeJS web application with basic functionality for user login and pulling data from MySql based on session information. The app is functioning as intended (Link). However, when I implement the client-side in React, the session data is ...

Rendering in Three JS involves efficiently utilizing one buffer to display the output within itself

I have been struggling with a particular issue and I really need some assistance: In my three js context, I have created a custom material and rendered it into a texture. ` /* Rendering in texture */ fbo_renderer_scene = new THREE.Scene(); fbo_r ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

How to access specific values from a deserialized JSON string using Javascript

Within the nested for loops, I have the following row: document.getElementById("sm" + i + "b" + j).innerHTML = jsonval.values.sm1b1; ^^^^^^ In order to change the va ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...