Decoding a formatted string

Here is a string that needs parsing:

const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'

The goal is to generate a JSON structure like this:

[{id: 'a', map: 'b'},
{id: 'foo', map: 'bar'},
{id: 'alpha', map: 'beta'}]

I am considering using regex for this task, but also exploring if there are any useful libraries available for this purpose.

Answer №1

If you're looking for a solution tailored to your specific situation, consider using the following regular expression:

const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");';

const res = str.split(";").map(e => {
  const k = e.match(/map\("(.+?)"\)to\("(.+?)"\)/);
  return k && k.length === 3 ? {id: k[1], map: k[2]} : null;
}).filter(e => e);

console.log(res);

The technique involves splitting the string on semicolons (with the option to handle semicolons within key/value pairs using lookaheads), then mapping these pairs into an object format defined by a regex that picks apart the map("")to("") structure. Finally, any resulting null elements are removed.

Answer №2

Although I'm aware that there might be a more concise and efficient regex solution, I tend to approach these types of problems in a different way due to my limited knowledge of regex:

const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'

const result = str.split(';').map(e => {

  const parts = e.substring(3).split('to').map(item => item.replace(/\W/g, ''));

  return {
    id: parts[0],
    map: parts[1]
  };
})
console.log(result);

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

Top pick for building drag-and-drop web applications: the ultimate JavaScript library

Up to this point, I've relied on jQuery UI's draggables and droppables for my projects. However, I recently came across ExtJS and other libraries that caught my interest. I am aiming to create a professional-grade plugin. Can anyone suggest the b ...

Changing the dataURL of jqGrid dynamically after loading the Edit Form

Currently, I am working with jqGrid version 4.15.6-pre, which is the free version of jqGrid. Within my edit form, I have two dropdown lists that are being populated from the server using setColProp in the onSelectRow function. My objective is to reload t ...

Improving the efficiency of JSON web services through Retrofit optimization

Currently, I am using Retrofit and have implemented the ItemTypeAdapterFactory class which implements TypeAdapterFactory and handles the read method. Everything is functioning perfectly, but I have noticed a significant slowdown when dealing with a large a ...

Encountering a timeout issue with the Sinch API within an Angular 2 project during the onCallProgressing

We successfully integrated Sinch into our angular 2 web application. Most functionalities are working perfectly, except for the user calling feature using the sinch phone demo. When the application is in the foreground, the call rings and connects withou ...

Decrease the space between slide items by reducing margins or increasing their width

I'm having trouble achieving the desired spacing between items, I would like more space between each item but they are currently too close together. I am looking for a margin of 10px or a width of 32% for each item. I have already looked into some re ...

Adding an element to a blank array using Angular

When attempting to add a new item to an empty array, I encounter an error: $scope.array.push is not a function. However, when the array is not empty, the push operation works flawlessly and updates my scope correctly. Just so you know, my array is initia ...

Secure your API routes in NextJS by using Passport: req.user is not defined

Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed. After successfully implementing authentication on my website using passport and next-connect based on a ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

How PHP Processes Fragment Identifiers within URLs

Looking for some advice from the community on a tricky situation I'm facing. Here's the issue at hand: I have developed a website with dynamic content pulled via AJAX and displayed using JS. To allow direct links to my content, I modify the frag ...

Explore the various advanced formatting options available for JSON serialization

I currently have data stored as objects within a list object that I need to serialize to JSON. I'm using JSON.NET for this purpose, but I've encountered an issue with the serialization process. JsonConvert.SerializeObject(list, ...) It seems th ...

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

Reconfigure the API to segment its components into individual variables

I'm currently working with an API that offers a wide range of available calls. In my VUE code, I am looking to modify it so that depending on which button is clicked, a different call is triggered. You can check out one example of this here: <> ...

Exploring database options for Android applications: Should you go with SQLite, or opt for mySQL and JSON instead?

Currently, I am developing an Android application that showcases a vast array of recipe names within a list view. Users have the ability to filter through this list and click on specific recipes to access more detailed information. The initial recipe list ...

End: unrelated, lacking responses

I have a question I'd like to discuss: Whenever I utilize the following code snippet: async function createNewElement(req,res){ const start1 = new Date().getTime(); console.log("start time 1 ", start1) await new Promise((resolve) => setT ...

Is it possible to utilize a specialized deserializer nested within another custom deserializer for GSON?

The following code snippet is designed to help convert JSON into an Object. If the String value is nil, it will be considered as null. This code includes two custom deserializers: MyOwnStringDeserializer and MyOwnListDeserializer. However, there is some d ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

Tips on retrieving individual ID data from a JsonObject in Android using the Retrofit library

Exploring the Android platform and encountering challenges with fetching data using Retrofit from a specific link. The link in question is meant to provide individual ID data, such as 1,2,3,... However, despite several attempts, no data seems to be coming ...

Unable to utilize the 'require' function in subdirectories within the node_modules directory

In the development of my express api, I have set up routes as a dependency within the main project. The main project contains a config folder with an index.js file that exports an object serving as the route configuration. While I can access this exported ...

What is the process for passing an Object from JavaScript to an Action class in Struts 2?

Within my Action class, there exists an object of the class that is a POJO. public class ConfigureTspThresholdAction extends ActionSupport implements SessionAware, ModelDriven<GmaThresholdParameter>{ private Map<String,Object> session ...