decipher the string using various operators

Is it possible to explode a string using different operators?

I am trying to extract every code (of varying sizes) between the brackets [ and ]

Here are some examples of the different possibilities:

const codes = [
   '[5018902847][592][50189272809][5089113805]',
   '[3898]',
   '[375001833][3475001021]',
    '',
]

And this is what I need:

[5018902847, 592, 50189272809, 5089113805]
[3898]
[375001833, 3475001021]
null // because code is empty

My initial solution looks like this :

codes.map(code => {
    const res = code.split('[ ' || '][' || ']');
    console.log(res)
})

However, the result does not match my expectation, for example:

[
  ' [5',
  '51889',
  '28475][5',
  '51889424192][5',
  '518892728',
  '9][5',
  '518891138',
  '5]'
]

Answer №1

You might want to consider utilizing the String.prototype.match() method in JavaScript

const values = [
  "[5018902847][592][50189272809][5089113805]",
  "[3898]",
  "[375001833][3475001021]",
  "",
]

const result = values.map((value) => {
  const extractedValues = value.match(/\d+/g)
  return extractedValues && extractedValues.map(Number)
})

console.log(result)

Answer №2

If you're looking to split a string using a regex separator, here's an example:

> '[5018902847][592][50189272809][5089113805]'.split(/[\[\]]/)
[
  '',
  '5018902847',
  '',
  '592',
  '',
  '50189272809',
  '',
  '5089113805',
  ''
]

To convert your codes array into a specific format, you can use this concise one-liner:

const codes = [
   '[5018902847][592][50189272809][5089113805]',
   '[3898]',
   '[375001833][3475001021]',
    '',
]
const cleanedCodes = codes.map(code => code.split(/[\[\]]/).filter(s => s.length)).filter(a => a.length)
console.log(cleanedCodes);
/*
 * Output will be: [
 *  [ '5018902847', '592', '50189272809', '5089113805' ],
 *  [ '3898' ],
 *  [ '375001833', '3475001021' ]
 * ]
 *
 */

Answer №3

This method does not require the use of match (taken from @hgb123's solution).

const codes = [
  "[5018902847][592][50189272809][5089113805]",
  "[3898]",
  "[375001833][3475001021]",
  "",
]

const result = codes.map((code) => {
  var extracted = code.split(']').filter(Boolean).map(x => {return x.replace("[","");})
  return extracted && extracted.map(Number)
})

console.log(result)

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

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Tips for defining a dynamic class variable in React with Flow

I am working with a map that assigns a reference to items, specifically in this scenario it is a video. const ref = this[`video-${index}-ref`]; I am seeking guidance on how to properly type this using Flow. The number of indexes may vary. ...

Record all GraphQL responses using Express

After successfully implementing logging for GraphQL errors using the provided code: app.use('/graphql', graphqlHTTP(request => { return { schema, rootValue: { request }, formatError: error => { const params = ...

Troubleshooting node modules for browser compatibility

Looking for assistance with running a specific node module in a browser. The module in question is called fury.js. I attempted to use browserify, however, encountered an error stating "ReferenceError: fury is not defined" when trying to utilize it. In th ...

Customize the appearance of a shadow-root element

Is there a way to modify the styles of a shadow element? Specifically, is it possible to extend or overwrite certain properties within a CSS class? I am currently using a Chrome extension called Beanote, which has not been updated since April 2017. There i ...

Using Vuejs to pass the SAVE function into a CRUD component

I am facing a challenge in finding a suitable solution that involves advanced parent-child communication in Vue.js. The scenario is such that there are multiple parent components, each with its own logic on how to save data. On the other hand, there is onl ...

Using Mocha in Node to make XMLHttprequests

Currently, I am experimenting with using node-xmlhttprequest. Here is an example of what I have been working on: // f.js (function() XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest xhr = new XMLHttpRequest() xhr.open('GET ...

javascript resize canvas to fit content

Is there a way to crop an HTML canvas based solely on its content? I've been using strokeText to create the canvas content, making it tricky to determine the actual size. Would it be possible to loop through each pixel of the canvas, or is there a mo ...

Executing the stop button in the browser with Webdriver IO

Just a bit of background: The program I'm testing is located within another website that requires login credentials. Once logged in, I can access the screen I need to test by typing in the direct link. However, there's an issue where my automated ...

Tips for verifying the request body when it consists of a lone JSON array

I am in the process of verifying the content of the request by utilizing the express-validator. The entire body is a singular array, which means there isn't a specific field name. Currently, I am making use of the new version of express-validator alo ...

Issue with displaying checkboxes in the dataTable table

I am currently working with dataTables and encountering difficulties displaying checkboxes on my tables. Below is the code that I have: <table id="employeeList" class="table table-sm table-bordered table-hover" cellspacing="0" width="200%"> &l ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

javascript strange behavior observed with multidimensional array

Looking to create a jquery autocomplete input that responds to the user's input from a previous field. I have a php script that returns a json variable, but I'm having trouble setting up my array correctly afterwards. I've attempted settin ...

Unknown individual, yet revealed by the investigator

I'm attempting to develop a dynamic list in react.js generateList = () =>{ return this.state.user.map((u)=>{ console.log(u); return <li onClick={this.handleClick} id={u} name={u}>{u}</li>; }); } The hand ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

How is it possible that I am receiving two different outputs, with one of them even being undefined

I created a button using Jquery to submit POST data. It sends the value "name" : "kevin" in JSON format. $(document).ready(function() { $('#clickMe').on('click', function() { var data = {}; data.name="kevin"; ...

Unable to trigger submission in jQuery validate function after validation check

I'm currently facing an issue with my form validation using the jQuery validate plugin. Although I have successfully implemented validation for the desired areas of the form, I am unable to submit the form even after filling in all the required input ...

Attempting to establish a login system using MongoDB

I am currently working on a function to verify user login details entered in a form and compare them with data stored in MongoDB, such as email and password. However, the function seems to be malfunctioning. The expected behavior is that when a user ente ...

PHP MySQL Table with a Date Range Filter

As someone who is new to PHP, I have a question. How can I set up a date range filter? I've looked at tutorials, but they haven't worked for me. I do have some code, but it doesn't include any functions. I want to implement this in a CRUD t ...

Avoid deleting a row in Sequelize if it is referenced in another association

Is there a method in Sequelize.js to trigger an exception when attempting to delete a row that is associated with another entity? For example, consider tables for Roles and Users. They have a many-to-many association, allowing any user to have multiple ro ...