Deciphering code snippets in JavaScript

Is there a way to extract shortcode information from a string and organize it in an array of objects? For example:

var str = 'First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in an array of objects like below';
var obj = parseShortcodes(str);

// obj now equals:

[
 {
  id: 'fraction',
  num: 1,
  denom: 2
 },
 {
  id: 'square-root',
  content: 456
 }
]

Answer №1

Here is a solution for handling complex shortcodes:

var extractShortcodes = function(str){
    var regex = /\[\S+(?:\s+[^="]+="[^"\]\s]+")+\]/g,
m, obj, result = [];

while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
regex.lastIndex++;
    }
    m = m[0].slice(1, -1).split(/\s+/);
    result.push(m.reduce(function(r, s){ 
        var pair = s.split('=');
r[pair[0]] = +pair[1].slice(1,-1);
return r;
    }, {id: m.shift()}));
}

return result;
};

var str = `First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in an object like below'`;

console.log(extractShortcodes(str));

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

In search of a downloadable demo showcasing a .Net service that can be accessed using a purely JavaScript client, eliminating the need for IIS to host the service

Trying to figure out how to set up this configuration has been quite a challenge for me. I've heard it's possible, but finding clear instructions has proven difficult. While I'm attempting to navigate my way through this process, maybe stack ...

Mapping strings to enums in Angular is an essential task that allows for seamless communication

Currently, I am facing an issue regarding mapping a list of JSON data to my model. One of the properties in my model is defined as an enum type, but in the JSON data, that property is provided as a string. How can I correctly map this string to an enum val ...

What are the steps to make ng-show functional in an AngularJS application?

I am attempting to implement a hover effect where an image is displayed over another image upon hovering over its container. I have been trying to achieve this using Angular and ng-show, but for some reason, the image with the ng-show attribute remains hid ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Error message indicates failure of switch case, resulting in invalid output of

My BMI calculator was working fine until I switched the conditionals to a switch statement for cleaner code. Now, the code is breaking and the result variable isn't being set properly for display. Do you have any ideas on what could be missing here? ...

Displaying the combined total for each date

My goal is to calculate the total for each department without duplicates ( which is currently working ) and display all results based on the selected date. I intend to select a date using md-datepicker and then only display the total task time where the d ...

"Troubleshooting: React Component Failing to Display Data Retrieved from API

Currently facing an issue in my React project where I am struggling to display fetched data from an API in my Movies component. Despite logging the data correctly in the console, it doesn't seem to show up on the page. Seeking assistance in identifyin ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

Utilizing Jquery for Enhanced HTML5 Validation

I need to ensure compatibility with browsers that do not support HTML5 validation. My goal is to display the basic error message from the browser using HTML5, while also adding a CSS class of "error" to each input, label, and parent div for fields with err ...

What is the method to deactivate multiple links using jQuery?

Below is the HTML code: <a title="Login" data-href="/MyAccount/Access/Login" data-title="Admin" data-entity="n/a" id="loginLink" class="nav-button dialogLink"><b>Login</b></a> <a title="Register" data-href="/MyAccou ...

Refresh the page to verify if the user has successfully established a connection with PhoneGap through AngularJS

I am currently developing an app using PhoneGap. I have successfully implemented a feature to check if the user is connected to the internet or not. However, if the user is not connected, I would like to provide a button for them to click on in order to re ...

The property 'titulo' of 'actividad' cannot be destructured because it is currently undefined

I'm currently utilizing the useParams hook to fetch a custom component. It successfully renders the id, but nothing more. Here's a snippet of my code: import React, { useState } from "react"; import { Link } from "react-router-dom ...

Inserting cards into an HTML document using JavaScript

I have a situation where I need to display 3 cards in a row instead of stacking them vertically. How can I achieve this? arr = [{ "Name": "Peter", "Job": "Programmer" }, { "Name": "John", "Job": "Programmer" }, { "Name": "Kev ...

Conceal the message using star symbols

I need help figuring out how to hide a certain type of string input from the user, and then use Angular data binding to display it in another component with part of the data masked with asterisks. I'm not very skilled in JavaScript, so I'm wonder ...

What steps should I take to troubleshoot and fix this issue with the pdf-generation

I am new to this field and currently working on developing a PDF generator web application with express.js using the html-pdf package. I have a condition based on the engagement variable. module.exports = ({rs, periode, engagement, siren, num, rue, codePos ...

Looping out of control

Here is my code snippet: var randomCoord = function(cells) { var step = $('.workplace').innerWidth()/cells; var xCord = (Math.floor(Math.random() * (cells+1)))*step; var yCord = (Math.floor(Math.random() * (cells+1)))*step; if(pl ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Decide whether Variable Name is equal to the String

I am currently facing an issue. var myArrayVariable1 = new Array(); var myStringVariable1 = 'myArrayVariable1'; var myStringVariable2 = 'myArrayVariable2'; Is there a way to determine if one of the strings matches the variable name? F ...

Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best. I am attempting to include a js file that imports json from an html .js import menus from '../json/menus.json'; (function () { function parseMenu(ul, menu) { fo ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...