In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challenge is that the splitting pattern for the codes is not fixed except for the format xxx-xx or xxx-xx-xx.

I attempted to solve this issue using a specific method but encountered difficulties in extracting the digits from the description part. Using \D captures anything that is not a digit.

let text = "[111-11] text here with digits 111, [222-22-22]; 333-33 text here";
let codes=[];
let result = text.replace(/(\d{3}(-\d{2})+)(\D*)/g,(str, code, c, desc) =>  {      
        desc = desc.trim().replace(/[\[\]']+/g,'');   
       if (code) codes.push({'code':code.trim(),'desc': desc});
        return str;
    }); //parse and split codes

My desired outcome is structured as follows:

[{code:'111-11', desc:'text here with digits 111'},
{code:'222-22-22', desc:''},
{code:'333-33', desc:'text here'}]

Your assistance in solving this problem would be greatly appreciated.

Answer №1

To extract values enclosed in brackets from a string and organize them into objects, you can use regex to match the bracketed values along with the surrounding text. By employing a positive lookahead for either another bracket or the end of the string, you can effectively destructure the matched strings and store them as desired objects.

const regex = /\[?(\d{3}(-\d\d)+)\]?(.*?)(?=\[?\d{3}(-\d\d)+\]?|$)/gm;
const str = `[111-11] text here with digits 111, [222-22-22]; 333-33 text here`;
var m,
    code, desc,
    result= [];

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }        
    ({ 1: code, 3: desc } = m);
    result.push({ code, desc })
}
console.log(result);

Answer №2

Here's another method to solve the problem:

const Separator = ','
const PatternSeparator = /[,;]/g
// Ignore spaces at the beginning, extract numbers (ignoring brackets if present), and capture the remaining text
const PatternPart = /^\s*\[?(\d{3}(-\d{2})+)]?(.*)$/


const source =
  "[111-11] text here with digits 111, [222-22-22]; 333-33 text here"

const parseSource = src => {
  // Normalize the source by replacing separators with a specific character
  const normalizedSrc = src.replace(PatternSeparator, Separator)

  return normalizedSrc.split(Separator).reduce((acc, part) => {
    // Extract code and description from each part
    const [_, code, __, desc] = part.match(PatternPart)

    // Store extracted data in an array
    return [
      ...acc,
      {code, desc}
    ]
  }, [])
}

console.log(parseSource(source))

;)

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 disappearance of the final element in an array after adding a new one using JavaScript

One of the challenges I'm facing in my backbone project involves creating an Add To Cart feature using window.localStorage. Below is my javascript code for the addToCart() function: var cartLS = window.localStorage.getItem("Cart"); var cartObject = ...

What is the best way to ensure that this jQuery window has a minimum size?

Recently, I came across a helpful jQuery demo that demonstrated how to create a popup window on my website. For those interested, the demo link can be accessed here: http://jqueryui.com/dialog/#modal-message The design of the window I am aiming to replica ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

The functionality of the webservice is not functioning properly

I'm currently working with Express and NodeJS to create a simple hello world webservice. I am attempting to call this webservice in ReactJS using Axios, but I am encountering issues with the response from the webservice. Below is my code for the webse ...

Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org: https://i.sstatic ...

Utilizing a child component in React to trigger a function on its sibling component

Trying to put this question into words is proving to be a challenge. I am wondering in React, if there is a way for a child component that is deeply nested (2 levels deep from the parent) to trigger a function on another component that it has a sibling rel ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

A guide on switching out an HTML element with an AJAX response

How can I dynamically replace an HTML element with Ajax response? I know how to remove the element, but I'm unsure how to then insert the new content from the Ajax call. For instance, let's say I have the following code: <ul id="products"> ...

Saving the output of mySQL queries on the client side for later use in subsequent requests

While logging a user in, I transfer attributes through a response object. In the javascript, I store specific attributes to a variable for future usage. For example, onresponse - currentUser = req.body.user currentID = req.body.id etc. Later, if I need t ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

javascript creating a module to extend a nested object

Currently, I am working on a JavaScript module that includes an object of default options. Here is a snippet of the code: var myModule = function() { // Define option defaults var defaults = { foo: 'bar', fooObject: { option1 ...

JavaScript causes the browser to freeze

When I execute this code, the browser freezes and I'm not sure how to troubleshoot it, can you assist? http://jsfiddle.net/z3DjY/1/ var levelArray = new Array(); var canvas; var ctx; var playerLocation; var edge; var elementEdge = 10; // Each elemen ...

What is the equivalent of defining conditional string types in Typescript similar to flow?

type UpsertMode = | 'add' | 'update' | 'delete'; interface IUpsertMembers { mode: UpsertMode; } const MagicButton = ({ mode: UpsertMode }) => { return ( <button>{UpsertMode}</button> ); } const Upse ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

Using GreenSock to animate and manipulate the tween function's parameters

I have two functions that are called on mouse events: function menuBtnOver(e){ var b = e.data; b.setPosition(b.x, b.y+5); } function menuBtnOut(e){ var b = e.data; b.setPosition(b.x, b.y-5); } Additionally, there is another function: setP ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Identify all div elements with a specific class within the parent div

How can I use query selector to exclusively target the p and p2 divs inside of a r class, without selecting them if they are outside of that class? <div> <div class="r"><div class="p"></div><div class="p2"></div></di ...