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

Exploring Angular's search functionalities using reactive forms

Hey there! I'm in need of some assistance. I'm currently attempting to perform a live search for elements that are both alive and responsive to case sensitivity when searching. My array, called elementsArray, contains fields such as: id, name, an ...

Troubleshooting Issue: Relative Paths Fail to Work with routerLink in Angular 6

I seem to be encountering a problem with the Angular app I'm currently developing. It appears that when using relative paths with routerLink throughout the application, it fails to work properly. There are no errors thrown and the navigation does not ...

Utilizing PrimeNG Datatable to Connect with an Array of Objects in a Dynamic Manner

I currently have an array of objects with various properties such as: "rows": [ { "id": 1, "createdAt": "2017-07-21T06:05:38.000Z", "updatedAt": "2017-07-21T06:05:38.000Z", "createdBy": null, "modifiedBy": null, "name": "ABC", "owner": "Dian ...

When using ngModel, the Tinymce Angular 2+ templates do not initially replace values, whereas they do when templates are inserted by the user

In my Angular 7 app, I am utilizing the TinyMCE editor component. When I insert a template variable into the editor: <span class="data-variable">${variable_name}</span> The variable gets replaced successfully with a value from the `template_r ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

The supabase signup function keeps showing me the message "Anonymous sign-ins are disabled." Can anyone help me understand why this is happening?

I'm currently in the process of setting up authentication in Next.js with supabase, but encountering an issue when attempting to execute the signUp function. The error message I'm seeing is: Anonymous sign-ins are disabled Below is the snippet o ...

What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module. index.svelte import {url} from '@roxi/routify'; someFunction(() => { let x = $url('/books') // this line needs to be mocked console.log('x: ' + x); }); ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

Development in Angular 2 with a team of developers utilizing TFVC for version control and managing node_modules

With over 20,000 files in the node_modules directory, it may not be practical to include them in source control. This results in developers having to run 'npm install' every time they perform a 'get latest' in order to download any mis ...

Typescript: parameter must be included if another is also required

In the user interface, the parameter c is mandatory only if the parameter a is set to true. interface IArguments { a: boolean, b: string, c: string } The solution below seems to be effective, but how can I exclude the c parameter in the first scenar ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

What are the steps for utilizing the watch feature in Vue.js with TypeScript?

Currently, I am looking to convert this JavaScript script into TypeScript. However, I require the syntax for watchers. export default { props: ['branch_id'], watch: {} } ...

Encountering a net::ERR_EMPTY_RESPONSE error while trying to use the DELETE Method in Angular 4

I have been using the following method to delete data: return this.http.delete(this.ApiURL, new RequestOptions({headers: headers,body: body })) .map((res: Response) => res.json()); However, I encountered the net::ERR_EMPTY_RESPONSE error. Interestingl ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

Eliminate the AM and PM options from the input time selection dropdown menu in HTML

I'm looking to eliminate the AM / PM option in this time input dropdown, can it be done? The form builder currently uses 24-hour format based on the presence of the AM / PM field. ...

Failure to update values in local storage using the React useLocalStorage hook

I've developed two unique custom hooks named useLocalStorage and useAuth. function getDefaultValue<T>(key: string, initialValue: T | null): T | null { const storedValue: string | null = localStorage.getItem(key); if (storedValue) { retur ...

Troubleshooting a Pulumi script in Azure using Typescript and encountering difficulties with function writing

My background is in using terraform, but now I am trying out Pulumi/typescript for the first time. In my codebase, I have two files - index.ts and blob.ts. The create function in blob.ts is responsible for creating a storage account, resource group, blob ...