What is the best way to convert a string into an object using JavaScript?

Here is a code snippet I have:

    const burger = `<div class="card" data-id="42" data-price="15" data-category="popular">`

I am trying to create the following object:

    const obj = { id: 42, price: 15, category: 'popular' }

To achieve this, I am using the following function:

let regex = /(?<name>\w+)="(?<value>\w+)"/g;
let results = burger.matchAll(regex);

for(let result of results) {
  let {name, value} = result.groups;
  let values = `${name}: ${value}`;
  console.log(values)
}

The output I am currently getting is not what I desire:

    > "class: card"
    > "id: 42"
    > "price: 15"
    > "category: popular"

Answer №1

If you want to parse HTML and extract attributes, you can utilize the DOMParser method. Simply retrieve the first child element and iterate through all its attributes.

To handle converting number and boolean strings into their respective data types, you can rely on functions like isNaN for numbers and basic string comparisons.

The parseInt() function is helpful for transforming a string into a number, while JSON.parse() can be used for changing a string into a boolean value.

const burger = `<div class="card" data-id="42" data-price="15" is-author-spectric="true" data-category="popular"><div class="card-category">Popular</div><div class="card-description"><h2>The best burger in town (15€)</h2></div></div>`;

const parser = new DOMParser().parseFromString(burger, "text/html");
const elem = parser.body.firstChild;
var json = {};
for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    json[attrib.name] = !isNaN(attrib.value) ? parseInt(attrib.value) : attrib.value == "true" || attrib.value == "false" ? JSON.parse(attrib.value) : attrib.value;
}

console.log(json);

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

Creating scalable Node.js applications with RabbitMQ: Tips for building a well-scalable app

What are your thoughts on using RabbitMQ as a message broker for scaling an application with socket.io in a Nodejs project compared to Redis? In what other scenarios could Rabbit be used, or are there more powerful tools available? What do you recommend ...

List that scrolls with a stationary button

I am working on an interface that includes a button with a dropdown list. Here is an example: <a href="https://jsfiddle.net/DTcHh/16589/" rel="nofollow">jsfiddle</a> While the list is scrollable, I am looking to add a fixed button at the botto ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Is it possible to activate every function within a prototype?

When presented with a class structure as demonstrated below, I am able to iterate through all its PropertyNames using console.log. class Security { constructor(param: ParamType) { this.method1(param); ... this.methodN(param); } method1(p ...

Is it possible to integrate various timers into Bootstrap datatables columns based on the provided dates?

I'm having an issue with adding a countdown timer to a table where it gets the due date value and displays the remaining time in a cell. It's currently working fine for one record, but when I add two or more rows, the timer from the last row dupl ...

What is the correct way to access the text of a selected radio button within a datalist

Within the dataset below, there is a collection of questions and answers. How can you use JavaScript to verify if the user has selected the correct answer radio button before clicking the submit button? The answers are stored in a database. Data List: & ...

The validation of form.$invalid appears to be malfunctioning when using the Angular UI date picker

There are two fields on the form, one for selecting a due date and another for entering a number. The due date field is a date picker where you can choose a date or manually enter a number to set the date. The create button gets enabled only when setting ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Introducing an alternative solution for handling tasks linked to the completion of CSS3 animations

In order to incorporate smooth CSS3 animations into my website, I have implemented the animate.css library created by Dan Eden. One particular scenario involves a loading screen that features a fade-out animation. It is crucial for this animation to comple ...

Steps for creating a duplicate of a chosen item in a dropdown menu

Is there a way to specifically select an item from a drop-down menu and duplicate it within the same list? I've come across several solutions where instead of cloning the selected item only, the entire list gets duplicated. For example: function Cop ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

Is there a quicker method to completely replace an element's DOM with another in jQuery?

Currently, I am utilizing jQuery's AJAX functionality to retrieve new content from the server in JSON format: $.ajax({ url: url, data: { 'ajax': '1', }, dataType: 'json', success: somefunction ...

Regular expression to identify the initial 28 days of the calendar month

Seeking a regular expression that will only match if a date falls within the first 28 days of the month. This is needed for implementing validation in an ASP.NET control. ...

Include a timer in the Promise.all and map function

I am seeking to enhance the interval between consecutive get requests below. The desired flow should appear as follows: timeout, https://example.com/example1, timeout, https://example.com/example2, timeout, https://example.com/example3, timeout, and so for ...

Unable to modify the content inside an HTML object using an anchor tag

I am currently working on a project for a client who wants to integrate three websites into a single browser window, allowing them to interact without opening multiple windows. Originally, I thought using iframes would solve the issue, but unfortunately, t ...

Access a remote server via SSH and run Node.js commands

I need assistance with SSHing into a virtual machine and running scripts within it using Node.js Currently, I have a shell script that handles the login process to the virtual machine, but I'm stuck on what to do next. This is the shell script I&apo ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

What is the best way to pass information from a child component to a parent component in ReactJS?

I am currently working on a project to develop a website that can adjust recipes for different serving sizes. Utilizing React, I have set up a component to handle the original servings, new servings, and number of ingredients. However, I am facing an issue ...

Send user to a designated webpage and execute JavaScript code upon the loading of said page

When redirecting from one page to another, there was an issue with executing some code. if (something === true) { /* Redirect to anotherpage.php */ window.location.href = "anotherpage.php" var test = "anotherpage.php"; /* On load of anoth ...

Tips for capturing changes in a "count" variable and executing actions based on its value

I have a counter on my webpage and I'm trying to change the style of an element based on the count variable. I tried using the .change action but I haven't been able to get it working. It might not be the right solution. Can anyone provide some ...