0

I have string like

"{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}"

How can I return object with key value with regex like. Many thanks!

{
  format: 'svg',
  width: 383,
  height: 480,
  transform: [40, 40, 40, 40],
  scaleX: 1,
  scaleY: 1
}
3
  • 2
    You seem to be trying to interpret the datatype of each value (eg string vs number vs array...) and turn it into a perfect javascript object. This will probably get convoluted with regex. I'd recommend looking for a different approach Commented Nov 1, 2022 at 9:27
  • 2
    Is there no way to tackle this by the source? What produces such a string? Is there any way to produce a more common object notation instead (JSON, XML, YAML)? Commented Nov 1, 2022 at 9:39
  • 1
    Please explain what other inputs you could get? Like, could arrays be nested, could there be inner objects, booleans, numbers in scientific notation, hex notation, dates, nulls,...etc, etc. Please make sure to completely describe the rules of the input format. Commented Nov 1, 2022 at 13:16

1 Answer 1

1

Here is a solution making several assumptions, which might differ from your needs:

  • keys are assumed to be alpha chars only
  • values that have a number pattern are assumed to be numbers
  • values that start and end with [ and ], respectively, are assumed to be a array containing numbers

const str = "{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}";
const regex = /([a-zA-Z]+)=(\[[^\]]*]|.*?)[,\}]/g;
let obj = {};
str.replace(regex, function(m, key, val) {
  if(/^-?\d+(\.\d+)?$/.test(val)) {
    val = Number(val);
  } else if(/^\[.*\]$/.test(val)) {
    val = val
      .replace(/^\[(.*)\]$/, '$1')  // get rid of `[` and `]`
      .split(/, */)                 // split on comma and optional space
      .map(num => Number(num));     // convert each item to a number
  }
  obj[key] = val;
  return '';
});
console.log(obj);

Output:

{
  "format": "svg",
  "width": 383,
  "height": 480,
  "transform": [
    40,
    40,
    40,
    40
  ],
  "scaleX": 1,
  "scaleY": 1
}

Explanation of regex:

  • ([a-zA-Z]+) -- capture group one for key
  • = -- literal = sign
  • ( -- start of capture group 2 for value
  • \[[^\]]*] -- pattern representing an array of form [...]
  • | -- logical OR
  • .*? -- non-greedy scan
  • ) -- end of capture group 2 for value
  • [,\}] -- expect a comma or a curly bracket
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.