Retrieve the array from within the string

Any suggestions on how I can extract the array from this string?

The current string is:

"['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']"

I need to extract it to look like this:

['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']

I attempted using regex but it didn't work as expected:

string.replace(/"/g, '')

Thank you for any help provided.

Answer №1

To maximize compatibility, consider generating a proper JSON string instead of the current format. However, if circumstances beyond your control require you to work with the existing format, you can utilize a parser that supports it (e.g. JSON5):

TS Playground

<script type="module">

import JSON5 from "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f9e0fcfda6d3a1bda1bda0">[email protected]</a>/dist/index.min.mjs";

const input = "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']";

const array = JSON5.parse(input);

console.log(array); // ["Biller.Customer.Data@Taxonomy", "Product.Platform and Enterprise Services Data.Data@Taxonomy"]

</script>

Alternatively, if you are aware of the risks associated with string evaluation, you may also opt for eval():

TS Playground

const input = "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']";

const array = eval(input);

console.log(array); // ["Biller.Customer.Data@Taxonomy", "Product.Platform and Enterprise Services Data.Data@Taxonomy"]

Answer №2

newList=(myArray.match(/\'([^,])*\'/g) ||[])
          .map(item=>item.slice(0,-1).slice(1))

Answer №3

If you need to work with JSON data that contains single quotes, consider using JSON.parse. However, keep in mind that single quotes are not valid string delimiters in JSON. You can use replaceAll to switch single quotes to double quotes if you did not generate the original string. On the other hand, if you have control over the initial string creation process, it's best to use double quotes as delimiters instead.

JSON.parse(yourString.replaceAll("'", '"'))
may seem like a solution, but be cautious as it carries some risks. If your strings contain apostrophes, they could render the JSON invalid, leading to errors when using JSON.parse.

Note: Take special care when handling single and double quotes within the replaceAll function.

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

Angular causing alignment issues for items not centered

I'm having trouble centering the contents of a div with my code. The properties I am applying don't seem to work. Any idea why this is happening? <div class='center'> <form (ngSubmit)="loginUser()" style="background: steel ...

Error message: Typescript class unable to access methods because of undefined properties (TypeError: Cannot read properties of undefined (reading 'method_name'))

During the compilation process, everything goes smoothly with no errors. However, when I try to call the method in the controller, an error occurs. It seems that some class methods are missing during the compilation phase. If you require more information ...

The power of absolute paths in React Native 0.72 with TypeScript

Hi everyone! I'm currently having some difficulty setting absolute paths in react native. I tried using babel-plugin-module-resolver, as well as configuring 'tsconfig.json' and 'babel.config.js' as shown below. Interestingly, VS Co ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Combine multiple HTTP service calls in Angular's NgRx store into a single effect and trigger corresponding actions

Hey there, I am currently trying to call multiple HTTP services in parallel using forkJoin, but after it's finished, the actions are not being dispatched. doSearchCliente$ = createEffect(() => this.actions$.pipe( ofType(addCliente), ...

Get the latest B2B department for the client within Spartacus

How can I display the current B2B Unit name in the header for the customer? I have been exploring ways to retrieve the B2B Unit for the current customer and found that there is a payload available for the /current? endpoint that loads on the initial page ...

Transform an Angular 2 application to seamlessly incorporate an SDK

I have been working on an Angular 2 application and I am curious if it is feasible to transform this into an SDK that can be easily integrated into other applications by simply adding script tags in their headers. If this conversion is not achievable, co ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

Is there a more concise method for accepting a collection of interfaces in TypeScript?

Issue I am facing a simplified version of a problem with my model: Here is how my model currently looks: interface Instrument { name: string; // ...more properties shared by all instruments... } interface Guitar extends Instrument { type: &q ...

Issue occurred while trying to deploy Firebase functions following GTS initialization

Objective: I am aiming to integrate Google's TypeScript style guide, gts, into my Firebase Functions project. Desired Outcome: I expect that executing the command firebase deploy --only functions will successfully deploy my functions even after init ...

Having trouble clicking on a button with Protractor because the button text is located within a child span element

Having trouble clicking a button with protractor. The DOM structure is displayed in the image above. Here are some of the locators I've attempted to use: element(by.xpath("(//div[@class='mat-drawer-backdrop ng-star-inserted'])//a followin ...

Angular2 experiencing issues loading boot.js file

Whenever I try to launch my project directly from file:///C:/wamp/www/ngProject/index.html or through WAMP at http://localhost/ngproject/, it always gets stuck on the boot.js file. Interestingly, in development mode with npm-start, everything works just f ...

After applying the withStyles and withTranslation higher order components to a React component, a Typescript error is displayed

Trying to create a React component using Typescript, incorporating withStyles from @material-ui/core and withTranslation from react-i18next, both of which are Higher Order Components (HOC). Encountering a typescript error when using them together. Specif ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

What is the method for declaring personalized environment variables in Angular?

I am looking to utilize a different environment variable called test. The purpose behind this is to set up an http interceptor for my integration tests. This interceptor should specifically return a mocked response with predefined data and is intended for ...

Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint. We maintain a dictionary of image files as follows: export function getAllImages(): {name: string, extension: string}[] { return [ {name: 'tile_lumber', extension: '.svg ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...