What is the best way to divide a string based on multiple conditions in JavaScript?

Can someone help me retrieve a specific value?

name // apple
index // 1
LastName //Surname

I am struggling with my current method due to a single condition '.'

value = '#[pill(apple.1.Surname)]'
const [var1, var2, var3] = value.split('.')

The regular expression is /#\[pill\((.*?)\)\]/gi

Answer №1

var example = '#[pill(google.0.LastName)]';

console.log(
  example.substring(example.indexOf('(') + 1, example.indexOf(')')).split('.')
);

console.log(
  example.match(/\(([^)]+)\)/)[1].split('.')
);

These are two different methods to achieve the same result: one using substring and the other using a regexp.

Answer №2

To avoid the need for splitting, you can make use of three matching expressions in your regex pattern like so: , #\[pill\((.*)\.(.*)\.(.*)\)\]

var string = "#[pill(google.0.LastName)]"
var [_, name, Index, LastName] = string.match(/#\[pill\((.*)\.(.*)\.(.*)\)\]/)

console.log(name, Index, LastName)

Answer №3

One way to break down the segments of the identified text is by splitting them.

const
    text = '#[pill(google.0.LastName)]',
    [firstPart, indicator, secondPart] = text.match(/[^\(]+(?=\))/)[0].split('.');
    

console.log(firstPart);
console.log(indicator);
console.log(secondPart);

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

Arranging buttons that are generated dynamically in a vertical alignment

Currently, I am in the process of creating a webpage for various items, and everything is going well so far. However, I have encountered an issue while attempting to vertically align the buttons that I am generating using JavaScript within the document. I ...

Utilizing variables to showcase a list nested within another

Within my code, I am trying to render two lists nested within each other, but I am unable to access the variable of the parent list inside the nested one. Can you help me identify where I might be making a mistake? <v-card v-for="n in lengthI" ...

The callback function in a JavaScript setTimeout() loop does not execute properly once the loop has completed

I've been facing a challenge in my recent JavaScript project. I've created two animations named DarkWaves and clearScreen. My goal is to pass a function (such as clearScreen) to DarkWaves, let it run its animation, and then execute the passed fun ...

Unable to export JavaScript module

In my JavaScript project, I have a module named utilities stored in a file called utilities.js. This module contains basic functions that I want to keep hidden from the global namespace. I know that in order to achieve this, I need to create a module, expo ...

Validation of dynamically added form fields in React

I recently developed a form in React with 2 fields, and I have successfully implemented functionality to add two more fields when the "add" button is clicked. However, I am now facing the challenge of validating these additional fields. Can anyone provide ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

Is it possible for the original object to be altered when passing it as a parameter to a function in a different file?

When you update an object passed as a parameter, will the updates be reflected "upwards" if the method receiving the parameter is in a different file? Or will the object retain its own context despite being passed down? ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

Combining two variables into a single form input using Ajax

In this section, I am populating a table where users can input quantities. <?php while ($row=mysql_fetch_array($select)) { ?> <td><?php echo $row['Size'];?></td> <td><input type="text" name="[<?php echo ...

Looking for a way to incorporate an image source property into a larger image?

I am working on a function that will enlarge an image when clicked on from a selection of 5 or more available images. The idea is that clicking on a small image will trigger the display of a larger version of that image in a frame. Here is an example of t ...

Unable to invoke Parse.Promise._continueWhile

I have attempted to use the conditional promise loop outlined below, but it never progresses to the second function. I have searched extensively for a solution, but have not yet found one. Any ideas you can provide would be greatly appreciated. Thank you. ...

Implementing AOP in NodeJS allows for executing a standardized process for handling database exceptions

Currently, I am in the process of developing a nodejs application that interacts with a database using Sequelize. One of my main requirements is to be able to receive an alert (in the form of an SNMP trap) whenever there are connection issues with the data ...

Executing jQuery AJAX Request to PHP File with JSON Response

I've hit a roadblock trying to solve this issue. I've attempted numerous solutions on stackoverflow without success! Essentially, when I make an AJAX POST request, the PHP returns JSON data, but the AJAX displays 'Undefined' instead of ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

``The functionality of `window.gapi` in the Gmail JavaScript library is currently experiencing technical issues

I recently integrated Google login into my React application using the https://www.npmjs.com/package/react-google-login library. However, I encountered an error stating Uncaught TypeError: Cannot read property 'load' of undefined. Upon further ...

Disable navigation bar icon for a specific page

I'm looking to disable the menu icon specifically on the menu page (normal page, not modal), but keep it active on all other pages. Using Meteor, React, and React-Router for my project. The diagram below illustrates the basic structure. Currently, I ...

When using a JavaScript object literal, is it more appropriate to use 'this' or the variable name for reference?

Struggling with object literal syntax and the use of "this" keyword was causing errors for me. However, when I replaced it with the object variable name itself, the issues disappeared. The error message I kept encountering was ''myFunction' ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...