Query the key value pair from a string object using regular expressions such as { key=value, .... }

I'm trying to extract key value pairs from a string using regex. Here's an example string:

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

How can I convert this string into an object with the following format? Any help is appreciated!

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

Answer №1

Below is a proposed solution based on a set of assumptions that may not perfectly align with your specific requirements:

  • The keys are assumed to consist only of alphabetical characters.
  • Values containing a numeric pattern are assumed to be numerical values.
  • If a value starts and ends with brackets, it is assumed to be an array containing numbers.

const data = "{type=pdf, size=1500, dimensions=[10, 20, 30], ratio=1.5}";
const regexPattern = /([a-zA-Z]+)=(\[[^\]]*]|.*?)[,\}]/g;
let resultObj = {};
data.replace(regexPattern, function(match, key, value) {
  if(/^-?\d+(\.\d+)?$/.test(value)) {
    value = Number(value);
  } else if(/^\[.*\]$/.test(value)) {
    value = value
      .replace(/^\[(.*)\]$/, '$1')
      .split(/, */)
      .map(num => Number(num));
  }
  resultObj[key] = value;
  return '';
});
console.log(resultObj);

Output:

{
  "type": "pdf",
  "size": 1500,
  "dimensions": [
    10,
    20,
    30
  ],
  "ratio": 1.5
}

Explanation of the regular expression used:

  • ([a-zA-Z]+) - capture group one for the key
  • = - matches the equal sign literally
  • ( - start of capture group two for the value
  • \[[^\]]*] - pattern representing an array enclosed in square brackets
  • | - logical OR operation
  • .*? - non-greedy match
  • ) - end of capture group two referencing the value
  • [,\}] - expect a comma or closing curly brace

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

An uncaught error has arisen within Electron-forge: [object Object]

After attempting to create an electron based application by executing npm run make in the terminal, everything seemed to be going smoothly until it reached the stage of Making distributables. Although the output folder was successfully generated, the appli ...

Unable to upload photo using Ajax request

I am in the process of trying to utilize Ajax to upload an image, so that it can be posted after the submit button is clicked. Here is the flow: User uploads image -> Ajax call is made to upload photo User clicks submit -> Post is shown to the user ...

In a set of numbers with a specific maximum sum, find the pair of numbers that can be added together to achieve the maximum sum

Looking for a solution that finds pairs in an array with a sum less than the maximum value: def findPairs(arr, x): left = 0; right = len(arr)-1 result = 0 while (left < right): if (arr[left] + arr[right] < x): ...

Disable Button's Shadow when it is in an active state (clicked)

Check out the DEMO to see the button animation CSS in action. The CSS code for the button animations is as follows: .btnliner { /* CSS properties */ } /* More CSS properties */ .btnliner:hover { /* Hover effects */ } Here is the corresponding J ...

What is the best way to align an image with the position of a div?

Looking for assistance on positioning an image to a div's position after it has been cloned. $(".raindrop1").clone().removeClass("raindrop1").appendTo("body"); $("img").css({"left": "div".x, "top": "div".y}); .shape{ border-radius: 50px; width: 10p ...

JSON at position 2 throws an error with an unexpected I token

Take a look at this code: <script> try { var jsonObject = JSON.parse("{ ID: 1, 'Code':'001', 'Name':'john', 'HasParent':false, 'HasGrandParent':false, 'IsAgent':False }&qu ...

Updating the titles of Bootstrap 4 Switches on the fly

Currently utilizing Bootstrap 4 Toggle on my website, I'm struggling to figure out how to dynamically modify the labels on the toggles at runtime. My objective is to implement a toggle-switch that, once activated, displays a countdown indicating the ...

Button that vanishes when clicked, using PHP and HTML

I am in the process of creating an online store and I am seeking to implement a button that directs users to a new page, but then disappears permanently from all pages within the store. Here is the code snippet I have developed so far: <input class="b ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

In Javascript, what significance does the symbol ":" hold?

While exploring the Ionic framework, I came across the following code snippet: import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: AlertController) { } I'm curious about the significanc ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Choose autocomplete feature from an external source within the context of AngularJS

I am currently working on an autocomplete textbox and I stumbled upon this script that I found through my search efforts. .controller('autoCompleteCTRL', function($scope, $rootScope){ $rootScope.searchItems = [ "ActionScript", ...

Enhancing animation with mouse movement in css [tips for improvement]

Greetings As I delved into creating a function that would cause a particular behavior (the closer you move the mouse to a div, the closer the div moves to the mouse position on the parent's X axis, with a maximum div position of left:-40% and a minim ...

Tips for handling an InvalidSelectorException in Selenium when logging into a website

I've been working on automating website logins using Selenium and here is the code I have written: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://abcde.com") assert "xxx" in driver.title user = driver.find_element_by ...

What is the best way to generate a frequency list by combining distinct arrays of varying lengths in numpy?

I am working with a collection of numpy arrays, each with varying lengths and some repeating instances. Here is an example: import numpy as np multi = [np.array([1, 2, 3]), np.array([1, 2]), np.array([1, 2, 3, 4]), np.array([1, 2, 3]), ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

I would like to receive a "null" response when parsing JSON in iOS

Looking to parse the following JSON data: "entry"[ {"id" { }, "published" { }, "content" { }, "link" [5], { "rel": "something", "type":"other stuff", "href":"h ...

Unexpected behavior exhibited by DOM elements

I can't seem to figure out this issue. Every time I run this loop: for ( var i=0; i < 10; i++ ) { var $items = $(balls()); console.log($items); $container.imagesLoaded(function(){ $container.append( $items ).masonry( 'app ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...