"Utilizing Regular Expressions and For Loops to Manipulate Strings: Splitting and

I am struggling to create a regular expression that can transform a string formatted like

(person,item(bought,paid),shipping(address(city,state)))
into a different format like this:

person
item
* bought
* paid
shipping
* address
** city
** state

My current knowledge of regular expressions is not sufficient for this task. I attempted the following approach, but it is not going to work:

var stg = "(person,item(bought,paid),shipping(address(city,state)))"
var separators = [' ', '\"\\\(', '\\\)\"', ','];
  stg = stg.split(new RegExp(separators.join('|'), 'g'));

Note: the structure of the string can change. My aim is to start a child element with * when a ( is encountered and close it when ). This might require a loop with conditional statements.

Answer №1

One option is to create your own custom iterator:

str = '(person,item(bought,paid),shipping(address(city,state)))';
counter = -1;
// Split and iterate
str.split(/([(,)])/).filter(Boolean).forEach(function(element) {
    if (element.match(/^[^(,)]/)) {
    console.log("*".repeat(counter) + ((counter > 0) ? ' ' : '') + element)
    } else if (element == '(') {
    counter++;
    } else if (element == ')') {
    counter--;
    }
});

Answer №2

Here is a clever way to achieve this using just one replace method:

str='person,item(bought,paid),shipping(address(city,state))';

var asterisks = '';
var result = str.replace(/(\()|(\))|,/g, (match, openP, closingP) => {
    if (openP) {
        return '\n' + (asterisks += '*');
    }
    if (closingP) {
        asterisks = asterisks.slice(1);
        return '';
    }
    // else: it is a comma
    return '\n' + asterisks;
});

console.log(result);

Answer №3

Why not consider using a JSON format rather than a multiline string? Here's the code:

var regex = /\((.*?)\,(.*?)\((.*?),(.*?)\),(.*?)\((.*?)\((.*?),(.*?)\)\)\)/;
var string = '(person,item(bought,paid),shipping(address(city,state)))';

var matches = string.match(regex)

var resultString = matches[1] + "\n";
resultString += matches[2] + "\n" ;
resultString += "* " + matches[3] + "\n" ;
resultString += "* " + matches[4] + "\n" ;
resultString += matches[5] + "\n" ;
resultString += "* " + matches[6] + "\n" ;
resultString += "** " + matches[7] + "\n" ;
resultString += "** " + matches[8];

console.log(resultString);

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

The entire component is not displayed in Vue

Just starting out with Vue. I'm looking to create a component that encompasses the entire page except for the header and footer Vue.component('main-block', {template: ` <section id="first-block">...</section> <secti ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

Transforming BufferGeometry to Geometry using FBXLoader within the Three.js library

Check out my snippet below for loading a .fbx object. It defaults to loading an object as BufferGeometry: const loader = new THREE.FBXLoader(); async function loadFiles(scene, props) { const { files, path, childName, fn } = props; if (index > fi ...

Error: Encountered an unexpected token F while trying to make a POST request using $http.post and Restangular

In our current project, we are utilizing Angular and making API calls with Restangular. Recently, I encountered an error while trying to do a POST request to a specific endpoint. The POST call looked like this: Restangular.one('aaa').post(&apos ...

Script tag in NextJS

After numerous attempts, I am still struggling with a specific task on this website. The challenge is to insert a script tag that will embed a contact form and newsletter sign-up form, among others, on specific pages of the site. For instance, the contact ...

Python code for arranging the output in numerical sequence

My program reads the last line of multiple files simultaneously and displays the output as a list of tuples. from os import listdir from os.path import isfile, join import subprocess path = "/home/abc/xyz/200/coord_b/" filename_last_l ...

Can someone please provide me with a Javascript code snippet that accomplishes the same function

<script> document.addEventListener('DOMContentLoaded', function () { const menuItems = document.querySelectorAll('.headmenu li'); menuItems.forEach(function (menuItem) { menuItem.addEventL ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...

Initiate a jQuery modal dialogue box

As an apprentice with no prior experience working with JavaScript, I encountered a problem with my function that calls a popup. The function works fine on the first button, but fails to work on all subsequent buttons. Since the application keeps adding b ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

How can jQuery retrieve a string from a URL?

If I have a URL like http://www.mysite.com/index.php?=332, can jQuery be used to extract the string after ?=? I've searched on Google but only found information about Ajax and URL variables that hasn't been helpful. if (url.indexOf("?=") > 0) ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

Tips on updating route and content dynamically without triggering a page reload while ensuring search engine indexing compatibility

I am curious to find a way to change the URL displayed and have it reflect different content on the page, all while ensuring that it is search engine friendly for indexing by robots. I have experimented with using AJAX for dynamic data loading and angular ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...