Home > other >  regex for stringify json
regex for stringify json

Time:11-20

I have the following string trying to remove clean with regex

 {"background-color":"rgb(11,144,213);","transform":"translate(11px, 144px) transform: skew(11deg, 144deg);"}

trying to find the right regex so that the final output would look like this:

 background-color:rgb(11,144,213);transform:translate(11px, 144px) transform: skew(11deg, 144deg);

I got this so far but not quite right

/[{[","|*"}]/g 

I'm really struggling with ","

CodePudding user response:

This is a non-regex solution

You can parse the string into an object, map through the entries and construct the string for each entry, then join the resulting array into a string.

const str = `{"background-color":"rgb(11,144,213);","transform":"translate(11px, 144px) transform: skew(11deg, 144deg);"}`

const res = Object.entries(JSON.parse(str)).map(e => `${e[0]}:${e[1]}`).join('')

console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Don't use regex for this - it's not a panacea for all string issues, particularly when you can...

  1. Parse the json to an object.

  2. Iterate over the Object.entries and add each key and value to a new string.

const json = '{"background-color":"rgb(11,144,213);","transform":"translate(11px, 144px) transform: skew(11deg, 144deg);"}';

const data = JSON.parse(json);
const entries = Object.entries(data);
let str = '';

for (const [key, value] of entries) {
  str  = `${key}:${value}`;
}

console.log(str);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

regex --> /((\",\")|([{\"}]))/g

const original = {"background-color":"rgb(11,144,213);","transform":"translate(11px, 144px) transform: skew(11deg, 144deg);"};

const modified = JSON.stringify(original).replaceAll(/((\",\")|([{\"}]))/g, "");
console.log(modified);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related