Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser:

eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()");

It will output THIS IS COOL, however, if you run the following:

eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS "NOT" COOL') + "')); })()");

It will not work as expected, failing to print THIS IS "NOT" COOL

Could anyone shed light on why this occurs?


Pay attention to this detail:

The outcome of

JSON.stringify('THIS IS "NOT" COOL')
is the string "THIS IS \"NOT\" COOL"

If you attempt to parse

JSON.parse("THIS IS \"NOT\" COOL")
, it will fail since the JS parser will interpret the string "THIS IS \"NOT\" COOL" as "THIS IS "NOT" COOL".

On the other hand, executing

JSON.parse(JSON.stringify('THIS IS "NOT" COOL'))
will work, as the string "THIS IS \"NOT\" COOL" is passed directly to JSON.parse.

Why does it succeed in one case, but not in the other?

I can only speculate that eval automatically unescapes any content passed to it before running the code, but I seek a definitive answer and understanding of why eval behaves in this manner.

Answer №1

The issue at hand stems from character escaping. Take a closer look at the output of the string concatenation:

"(function() { console.log(JSON.parse('"THIS IS \"NOT\" COOL"')); })()"

It's important to note that this is the true result, not a literal string. The \ in this context is a literal character, not an escape character (the quotation marks around it are only to signify that it refers to a string).

When using eval, the string is interpreted as follows:

(function() { 
    console.log(JSON.parse('"THIS IS \"NOT\" COOL"')); 
})()

Here, the \" are seen as character escape sequences, meaning the actual content of the string literal '"THIS IS \"NOT\" COOL"' is:

"THIS IS "NOT" COOL"

resulting in an invalid JSON encoded string.

Consequently, the encountered error is:

SyntaxError: Unexpected token N


eval doesn't modify the input string in any way; it interprets it as is.

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

Using urllib and json to store data in a variable

Can you please review my code? I'm attempting to save the content of this webpage in JSON format into a Python variable. Error: Traceback (most recent call last): File "C:/Users/Varen/Desktop/json_v1.py", line 5, in <module> json.dump(li ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Components not reflecting custom theme settings

I've been struggling to implement my custom theme, which consists of a simple color change, from Theme.js to the components in App.js. Despite my efforts, the components continue to display the default theme colors and I have been unable to change the ...

What is the relationship between JavaScript and the height of a window?

Consider the code snippet below: 24 <script type="text/javascript"> 25 26 function UpdateDisplay($isVisible){ 27 if($isVisible) 28 $('.relatedContent').stop().css({ 29 "transform": "tr ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

Don't forget to save the selected date in the datepicker

I have a datepicker with two text fields: fromdate and todate. When I input the month of May and submit, then input another date, the default date should remain as May, instead of changing to the current month. Check out my code below. $(function() { ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

The Firefox form is experiencing issues when the cursor is set to 'move'

I have an HTML form with a specific code snippet: #stoppage_section .stoppage{ cursor: move; /* fallback if grab cursor is unsupported */ cursor: grab; cursor: -moz-grab; cursor: -webkit-grab; } <div id="st ...

How to Force a jQuery Redraw Following Data Retrieval Using Ajax

Hey everyone, It's been a long time since I started listening, but this is my first post... I have a client who needs a complex feature on their website. They want to merge the content of 3 different pages into one seamless experience for users afte ...

Searching for a way to detect when a user clicks the back button on their Android or iPhone device using JavaScript or

In the process of building a Single Page Application (HTML5) utilizing the following plugins: - Sammy.js - Knockout.js - Require.js - Jquery.js This app is designed for Android, iPhone, and Windows mobile devices. Many scenarios revolve around cli ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

"Fixing issue with Checkbox not getting checked using a combination of jQuery and

My array called `totalCheckBoxArray` contains the values [1, 2, 3]. I also have checkboxes with values 1, 2, and 3: <div class="card-body"> <h5>Document List</h5> <div class="form-check"> ...

Make Bootstrap Panel Full Width with Highcharts Data

I am currently working on displaying graphs using the Highcharts library on three televisions. All televisions have a FULL HD resolution of 1920 x 1080. I have one Bootstrap panel containing a graph in the panel-body. <div class="panel panel-blue"> ...

Paused momentarily to allow user input

I am currently developing a new game where the player and enemies are stored inside objects with various properties. For example, each object includes: $player->health $player->attack (which represents attack power) Additionally, there is a PHP fun ...

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols. (), ||, and ++ are the symbols I'm using. If a text is enclosed in | symbols, it will appear in blue, and so on... Here is the code in action: const text = "|Working on the| i ...

I am looking to implement a permanent change using PHP Ajax

I am facing an issue with the "Add as Buddy" button on my webpage. I want it to change permanently to "Pending Request" once clicked, but it keeps reverting back to "Add as Buddy" whenever I refresh the page. Can anyone suggest a solution for this problem? ...

Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each... myArray[ { ...