Decode the string containing indices inside square brackets and transform it into a JSON array

I have a collection of strings that contain numbers in brackets like "[4]Motherboard, [25]RAM". Is there a way to convert this string into a JSON array while preserving both the IDs and values? The desired output should look like:

{"data":[
  {"id":"4","item":"Motherboard"},
  {"id":"25","item":"RAM"}
]};

I attempted using split(",") to parse the array but I am struggling to extract the inner data in this scenario.

Answer №1

To extract numbers and strings from a given text, you can utilize a regular expression to achieve this task. By applying the regex pattern on the input string, you can then store the extracted values as properties within an object.

var text = "[4]Motherboard, [25]RAM",
    dataArray = text.split(', ').map(function (item) {
        var result = item.match(/^\[(\d+)\](.+)$/);
        return { id: result[1], component: result[2] };
    });
console.log(dataArray);

Answer №2

Here's a simple way to accomplish this task using the pattern \[(\d+?)\](.+):

  1. The (…) is a capture group, indicating that whatever matches within the brackets will be saved as a token.
  2. \d represents a single digit.
  3. \d+ means one or more digits in a row.
  4. \d+? signifies one or more digits, but matching the fewest possible before moving on.
  5. .+ matches any character at least once.

In regular expressions, [ and ] have special meanings, so if you want to include them literally, you must escape them like so: \[ and \].

The double backslashes \\ are used in JavaScript as an oddity when defining a regex from a string rather than using the /literal/ notation. Both methods achieve the same result.

There are numerous resources available for learning regex patterns, and http://regex101.com is an excellent platform for testing and experimenting with different patterns.

var input = "[4]Motherboard, [25]RAM";
var pattern = '\\[(\\d+?)\\](.+)';
var result = input.split(',').map(function (item) {
  var matches = item.match(new RegExp(pattern));
  return {id: matches[1], val: matches[2]};
});

console.log(result)

Answer №3

function convertStringToArray(input) {
    return {
        elements: input.split(",").map(function(item) {
            item = item.trim();
            return {
                identifier: item.substring(1, item.indexOf("]")),
                value: item.substring(item.indexOf("]") + 1),
            };
        }),
    };
}

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

Dealing with parsing JSON push notifications while the application is inactive

Dealing with push message send via parse.com has been a challenge for me. When the app is running, I am able to handle JSON and construct messages using: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInf ...

Adjust the alignment and floating of text within an iframe on the same domain

Is it possible to align text on the right side of an iframe that contains a width and text inside? The iframe's src is from the same domain. If so, how can this be achieved through JavaScript? ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

Connection lost from JS client in Twilio's Programmable Chat

My React application utilizes the Twilio Programmable Chat library for chat functionality. The setup code typically appears as follows, enclosed within a try/catch block: this.accessManager = new AccessManager(twilioToken.token); const chatClientOptio ...

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

Positioning a div on the right side of its parent div

Hi there! I'm currently working on a small navbar that has two sections: the left section with an arrow icon and the right section with two icons - an envelope and an exclamation triangle. I've been trying to position the right section in the top ...

Guide to showcasing object characteristics inside an object in Angular2

My USAFacts object contains properties like StateName, as well as objects like State-Bird which hold information about the state bird. If written in JSON, a record of USAFacts would appear as follows: {"StateName": "PA", "State-Bird": [ { "Name": "Ruffed ...

Preserve the Browser Scroll Position when navigating to another page

Currently tackling a challenge with JS, JQuery, and PHP where I'm attempting to resolve an infinite scroll issue. The specific problem arises when scrolling down the page extensively while loading more pages via ajax, then navigating to a different pa ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

"Challenges Encountered When Implementing CSS Card Flip

Can anyone help me with a strange problem I'm experiencing with my css card flip code? The card seems to only flip when I move my mouse away from it. Any insights on what might be causing this behavior? Thank you in advance for any assistance. ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Trigger a click event on a nested Angular 13 component to remove a class from its grandparent component

In my Angular 13 project, I am working with 3 components: Child Component : Burger-menu Parent Component : Header Grand-Parent Component : app.component.html Within the burger-menu component, there is a close button. When this button is clicked, I want t ...

The functionality of passing POST variables to the model seems to be malfunctioning in PHP CodeIgniter when attempting to use the

I attempted the code snippet below: function doAjax() { var sList = ""; $('input[type=checkbox]').each(function () { var sThisVal = (this.checked ? "1" : "0"); ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

What is the solution for the error message "Unhandled Runtime Error" with the description "TypeError: videoRef.current.play is not a function"?

I am currently working on implementing custom controls for a video on a Nextjs website. When using a standard HTML <video> component, the code functions as expected and clicking the custom play button successfully plays the video. However, when I swi ...

Having trouble getting any results from a JSON response using the jQuery Tokeninput plugin in PHP?

I am currently trying to implement the JQuery Tokeninput feature on my website. However, when I enter text into the search field, nothing appears and it just continues searching indefinitely... After reviewing the documentation, I noticed that the expecte ...

Error occurred while executing 'npm start' command in ReactJS due to the module 'babel-code-frame' being unable to be located

Every time I attempt to run 'npm start' in the frontend of my application, the terminal spits out a massive error. My package.json file doesn't show any script errors, and I've deleted the 'node_modules' folder and reinstalle ...