Substituting characters, backslashes, and double quotes may not function properly

Trying to replace a single backslash \ with two \\, but encountering issues with double quotes.

var json = {
    "DateToday": "2021-08-11",
    "MetaData": [
        {
            "id": "222",            
            "nameUsed": " \"data\" somemorefillerdata» - somemorefillerdata «somemorefillerdata»",
            "type": "movies"
        }
    ]
}

let newJson = JSON.stringify(json)
let newnewJson = newJson.replace(/\\"/g, "\\\\");
let newnewnewJson = JSON.parse(newnewJson)
console.log(newnewnewJson)

Although it kind of works, the output is missing the quotes as shown below:

{
  DateToday: '2021-08-11',
  MetaData: [
    {
      id: '222',
      nameUsed: ' \\data\\ somemorefillerdata» - somemorefillerdata «somemorefillerdata»',
      type: 'movies'
    }
  ]
}

Answer №1

There doesn't seem to be a need to replace \ with \\. In this scenario, an object literal serves as the starting point. It is then converted into a string using `stringify`, producing the expected output. The string is then parsed back into an object, resulting in the anticipated outcome.

let personObj = {
  Name: "John Doe",
  Age: 30,
  Occupation: "Developer"
};

let personStr = JSON.stringify(personObj)
console.log(personStr);

let newPersonObj = JSON.parse(personStr)
console.log(newPersonObj.Occupation)

Answer №2

Whenever you find the need to insert an additional backslash, make the following adjustment:

let updatedJson = newJson.replace(/\\"/g, `\\\\\\\\`);

Based on my interpretation of the query, your goal is to achieve this result:

" \\data\\ somemorefillerdata» - somemorefillerdata «somemorefillerdata»"

Prior to the update, it appeared as follows:

" \data\ somemorefillerdata» - somemorefillerdata «somemorefillerdata»"

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

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

Tips for aligning the camera to ensure the object maintains a consistent pixel width and height on the screen

I am grappling with a challenge that I'm unsure how to approach, hoping someone can offer me a clue on the solution. My goal is to position the camera at a specific z index so that a cube appears on the screen with consistent pixel dimensions regardl ...

Adding multiple elements with varying content to a separate division

I am attempting to combine two div elements into a single div, but I'm encountering difficulties. Despite thoroughly examining my code, everything appears to be correct. Here's what I've tried so far. To assist me in achieving this, I am ut ...

Is there a way to copy this JavaScript variable and modify the displayed text?

I am working on a JavaScript code that is used to create a basic news page with a filter from a mySQL database. The code generates the heading, main content, and date created for each news item. I now need to add a "read more" link at the bottom of each ne ...

Maximizing CSS opacity for optimal performance in image fading

I'm working on creating a smooth fade in-out effect for the images in my photo gallery by adjusting the CSS opacity value using JavaScript. However, I've noticed that this process is quite sluggish on certain computers, such as my relatively new ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

Determine whether the JSON object has been declared

Having trouble determining if the value of values[item]['total'] is defined in a JSON object. The variable item is obtained from the select box value and I am attempting to use an if-else statement to check if values[item]['total'] is ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Ajax: The seamless integration of loading multiple images simultaneously

I have a grid of images (3x3) that need to be updated periodically. Each image is loaded independently through an ajax callback method, like this: for (var i=0; i < numImages; i++) { Dajaxice.loadImage(callback_loadImage, {'image_id':i}) } ...

The significance of 'this' in an Angular controller

Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding. Let's dive into JavaScript: var firstName = "Peter", lastName = "Ally"; function showFullName () { // The "this" inside this func ...

Troubleshooting Node-Red: Issues with JSON Parsing

I am currently working on extracting data from the things network using MQTT. However, I'm struggling with parsing the data correctly and storing each piece of information in separate variables. Here is the output obtained from the debug: {"payload" ...

Creating a dynamic jQuery object with JSON data for JustGage is a straightforward process that involves manipulating the

I am looking to use JustGage to display data from a MySQL database dynamically. My request successfully retrieves all the necessary data, and the file getData.php is functioning perfectly. However, when attempting to loop through this data, I encounter an ...

Discover the secrets to acquiring cookies within a Next.js environment

I am currently working with Next.js and attempting to retrieve a cookie value. Below is the code I have written: import cookie from "js-cookie"; export default function Home({ token }) { return ( <div className="flex flex-col items ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

Retrieving PHP information using Javascript and storing it in an array

I have a PHP script that fetches data from a server and stores it in an array. I then convert this array into a JSON object using the following function: echo json_encode($result); Now I want to access this array in my JavaScript and display it. I want t ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...

Using the highcharts-ng library in combination with ng-repeat was successful in creating multiple charts. However, in order to display different data for each chart, the

I need to provide the date either from the view template or possibly from the controller in order for the highchart to display the data specified by the <highchart /> directive. Explanation : <ul> <li ng-repeat="li in list"> ...

The active link for pagination in CodeIgniter is malfunctioning

Even though there might be similar posts on StackOverflow, my situation is unique. Hence, I have decided to ask this question with a specific title. Let me break down my issue into smaller parts: Part - 1: I have a regular view page where I can select a ...

Synchronize one file between numerous applications

I manage a handful of small web applications for a small team at my workplace. These apps share a similar layout and file structure, with many files being identical across all of them. For instance, the index.js file in the src/ directory is consistent in ...

JSON parsing error within the HTML Sidebar list

I have a JSON file that contains data I need to parse in order to display information in my sidebar. When a user clicks the button labeled "List all sessions", the goal is to showcase all of the available session details grouped by Session ID and location. ...