Eliminate blank double quotation marks in a JavaScript string

Hey there! Currently, I'm working on tidying up a JSON string. Let me show you an example of what I have:

" .tagline-wrapper ":{
" padding-top":"398px",
" font-size":" 1.8rem",
" "
},
".tagline ":{
" padding-top":"398px",
" font-size":" 1.8rem",
" ",
},
".wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
"",
},

My goal is to eliminate the double quotes that are either empty or contain white space (which can include multiple spaces). I've attempted to get rid of consecutive white spaces and then replace quotes like this:

str = str.replace("\" ","");
str = str.replace("\"\"","");

However, these methods haven't been successful. I also need to remove the commas. If possible, I'd like to eliminate consecutive commas while disregarding any white space. If you could assist with that too, it would be greatly appreciated. The desired output should look like this:

" .tagline-wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
},
".tagline":{
" padding-top":"398px",
"font-size":" 1.8rem",
},
".wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
},

This way, I'll be able to parse the JSON smoothly.

Answer №1

Have you considered using regular expressions to look for a " followed by any amount of white space followed by another " followed by an optional comma?

const str = `      " .tagline-wrapper ":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         " "
      },
      ".tagline ":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         " ",
      },
      ".wrapper":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         ""
      },`;
      
console.log(str.replace(/"\s*",?/g, ''))

Answer №2

In my process, I sanitize your string and attempt to use JSON.parse in order to transform it into an object.

Note: The replaceAll function is accessible in Nodejs version 15.x.

const str = `" .tagline-wrapper ":{
  " padding-top":"398px",
  " font-size":" 1.8rem",
  " "
},
".tagline ":{
  " padding-top":"398px",
  " font-size":" 1.8rem",
  " ",
},
".wrapper":{
  " padding-top":"398px",
  " font-size":" 1.8rem",
  ""
},`;

const cleanStr =
  "{" +
  str
    .replaceAll('" ', '"')
    .replaceAll(' "', '"')
    .replaceAll('""', "")
    .replaceAll(",\n ,", ",\n")
    .replaceAll(",\n\n}", "}")
    .replaceAll(",\n \n}", "}")
    .slice(0, -1) +
  "}";

console.log(cleanStr);
const object = JSON.parse(cleanStr);
console.log(object);

Answer №3

Give this code a try, it might be useful

function modifyJSON(input) {
    input = input.replaceAll('"', "'");
    input = input.replaceAll(/(\n\s*)/g, '');
    input = input.replaceAll(/(,?\n?\s?'\s*',?)/g, "");
    input = input.replaceAll(/},$/g, "}").replaceAll("'", '"');
    let parsedData = null;
    try{
        parsedData = JSON.parse(`{${input}}`);
    }
    catch{
        console.log(input);
    }
    return parsedData;
}

let data = `" .tagline-wrapper ":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         " "
      },
      ".tagline ":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         " ",
      },
      ".wrapper":{
         " padding-top":"398px",
         " font-size":" 1.8rem",
         ""
      },`;

console.log(modifyJSON(data))

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

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Adjust screen presentation based on chosen selection

Is it possible to use jQuery to dynamically change the styles of two different div elements based on a select option? When the value is set to div1, the first div should be displayed, and when the value is set to div2, the second div should be shown. Can ...

Exploring Javascript object properties in an array and matching them against a specific value

Can someone provide a clear explanation of my question using an example? I have an array of objects structured like this: [{a:"a",b:"",c:"c"}, {a:"a",b:"b",c:""}, {a:"",b:"b" ...

Exploring the concept of String Enums through Reverse-Mapping

I was exploring the use of string enums in TypeScript and came across an issue with reversed mapping support. Here's what my enum looks like: enum Mode { Silent = "Silent", Normal = "Normal", Deleted = "Deleted" } I want to be able to pa ...

Managing websites on Android when the keyboard is displayed

I am currently facing an issue with my webpage on Android (Galaxy SIII). The problem occurs when visitors try to enter their email in the form at the bottom of the page. The keyboard becomes visible, causing the design to look messy. When using Chrome, the ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

Incorporate JavaScript code within a Document Object Model (DOM

Looking for guidance on why I am experiencing difficulty adding JavaScript to a DOM var scriptString = "<script type='text/javascript'></script>"; $("#someElement").append(scriptString); ...

Is there a way to access the dimensions of a Bootstrap 4 popover?

I'm attempting to dynamically retrieve the height/width of the Bootstrap popover. I have the context in which I'm trying to grab the height/width: console.log(context); console.log(context.getBoundingClientRect().height); console.log(context.get ...

Tips on storing JSON string array with multiple name/value pairs in distinct arrays using JavaScript

Below is a JSON string that I have: [ { "id" : "1", "name" : "name1" }, { "id" : "2", "name" : "name2" }, { "id" : "3", "name" : "name3" }, { "id" : "4", "name" : "name4" }, { "id" : "5", "name" : "name5" } ] Is there a way to split this data into two se ...

Master the art of string slicing in JavaScript with these simple steps

I am attempting to utilize the slice function to remove the first three characters of a string within a JSON object. $(document).ready(function() { $.ajaxSetup({ cache: false }); setInterval(function() { $.getJSON("IOCounter.html", functio ...

Is it possible to access a variable that is outside the scope of a function without declaring it as a global variable (window.hazaa)?

I am working with a list of elements and applying a function to each one. This function calculates a subtotal that I want to add to a grand total. To avoid cluttering the window object, I defined the variable in my script right before declaring the list. ...

Looking for user-friendly and comprehensible guides on jQuery and JavaScript?

Seeking recommendations for a great jQuery and JavaScript book! With the overwhelming number of options out there, I am in need of some guidance. Any suggestions on truly remarkable books that are worth investing in? My understanding of these technologies ...

Unable to bring in a three.js glTF model

Recently, I've been attempting to incorporate a 3D module into my three.js project. In my quest for answers, I delved into the documentation available here and here. However, no matter what I tried, all I saw was darkness. I even adjusted the Camera&a ...

jquery plugin for creating Excel-like filters

I am in the process of creating Excel-like filtering for my dynamic table. To achieve this, I am utilizing a jQuery plugin that can be found at https://github.com/chestercharles/excel-bootstrap-table-filter. The reason why I chose this plugin is because it ...

Each time I attempt to navigate to a different component by clicking on a button, I have experimented with using Link and Routes in React, but have been unsuccessful in

After clicking on a button following the first h1 tag, I want to open the AddProjects Component. However, despite using react-router-dom, an error keeps showing up. I think I might be using it incorrectly. Please help me correct it. import React from " ...

Tips for ensuring Angular 5 applications are compatible with older versions of Firefox

How can I ensure my Angular 5 application is supported by older versions of Firefox (43, 44..)? The issue arises when there is an empty path in the route configuration like {path: '', redirectTo: 'view', pathMatch: 'full'}, ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Is there a distinction in functionality when utilizing fat arrow syntax versus traditional syntax for ES6 class methods and React?

Consider these two examples showcasing different ways to write an ES6 class method: The first example uses the non-fat arrow, or concise method syntax: class Test extends Component { handleClick() { return 'clicked' } } The second exam ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...