Substitute variables in a string and retrieve an array with typescript

I am trying to figure out how to manipulate a string that looks like this -

"{var1} apples, {var2} oranges are expensive". 

in combination with an object, which has the following structure -

{ 
  var1 : <Link to="xyz">5</Link>,
  var2 : <Link to="pqr">6</Link>
}

My goal is to create a generic method in TypeScript that can take in a string and object as input, and based on the keys of the object, generate an array similar to this pattern -

[
<Link to="xyz">5</Link>,
" apples, ",
<Link to="pqr">6</Link>,
" oranges are expensive."
]

Answer №1

Give this a shot:

const message: string = '{var1} cats, {var2} dogs are adorable';

const variables = {
    var1: '<Link to="abc"> 7 </Link>',
    var2: '<Link to="def"> 8 </Link>'
};

const placeholders: string[] = message.split(/[{}]/).map(placeholder => variables[placeholder] || placeholder);

console.log(placeholders);

Check for any unnecessary empty strings at the beginning

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 typing library for Angular does not properly identify the JQueryStatic object

Encountered an issue with the Angular declaration file: Error TS2304: Cannot locate identifier 'JQueryStatic'. The typings for jQuery are installed and properly declare JQueryStatic as an interface. Looking for solutions to resolve this error. ...

Retrieve the value of the corresponding array element during the current loop iteration

void main() { var n = 5; var x = 1; var a = [2, 5]; for (x = 1; x <= n; x++) { if (x == a[x]) { // highlighting the values 2 and 5 on 2nd & 5th iteration print(a[x]); } else { print(0); } } } The expected output i ...

What is the process for enabling the isolatedModules=true option when creating a package?

When exporting all the classes from my package in a file, I use lines similar to the following: export {default as BoundList, IBoundListOption, TBoundListFilterFn} from './list/BoundList'; This generates errors like: TS1205: Cannot re-export a ...

A more efficient approach to specifying types for the 'navigation' object in React Native's Stack Navigator

Struggling with modularizing prop types in React Navigation, particularly when using TypeScript. The Typescript section of the React Navigation documentation suggests defining types for each screen props in this manner: //types.ts export type RootStackPara ...

Transform JSON arrays into JSON structure

I'm currently facing an issue with converting JSON arrays to JSON format data. The output I am currently getting looks like this: https://i.stack.imgur.com/SW2NW.png However, I would like my output to be in the following format: https://i.stack.img ...

Convert a JSON array back into an object in C#

I have come across a rather unique JSON array: [["1","hello"],["2","hello2"],["3","hello3"],["",""],["",""],[null,null],[null,null],[null,null],[null,null],[null,null]] Attempting to de-serialize it in C# has proven challenging, as there is no common m ...

When using RXJS, the method BehaviorSubject.next() does not automatically notify subscribers

In my project, I have a service set up like this: @Injectable({ providedIn: 'root' }) export class MyService { private mySubject = new BehaviorSubject({}); public currentData = this.mySubject.asObservable(); updateData(data: any) { ...

Choosing the Active Browser Tab while Modal is Open in Angular

In my current situation, I have implemented a function in the first tab that displays a modal or component after 5 seconds: ngOnInit() { setTimeout(() => { this.openDialog(); }, 5000); } openDialog() { this.dialog.open(.....); } However, if ...

What is the best way to create and manage multiple collapsible Material-UI nested lists populated from an array with individual state in React

In my SideMenu, I want each list item to be able to expand and collapse independently to show nested items. However, I am facing the issue of all list items expanding and collapsing at the same time. Here is what I've attempted: const authNavigation ...

Java SudokuSolver starting point for FileNotFoundExceptionSolution

I've been encountering an issue when running my program: Exception in thread "main" java.io.FileNotFoundException: samplesukodu8.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Fi ...

Storing checkbox status in Angular 7 with local storage

I am looking for a way to keep checkboxes checked even after the page is refreshed. My current approach involves storing the checked values in local storage, but I am unsure of how to maintain the checkbox status in angular 7 .html <div *ngFor="let i ...

An unexpected token was discovered by Jest: export { default as v1 } when using uuid

While working on writing Jest tests for my React component in a Monorepo, I encountered an error while running the Jest test. ● Test suite failed to run Jest encountered an unexpected token... ...SyntaxError: Unexpected token 'export' ...

Add a custom design to the Material UI menu feature

I am currently trying to implement a custom theme using the following code: import Menu from '@material-ui/core/Menu'; import { createStyles, withStyles, Theme } from '@material-ui/core/styles'; const myMenu = withStyles( ( theme: The ...

Incorporating a module from a nearby component repository into the primary task

As I work on developing a component library using React, TypeScript, Rollup, and Styled Components, I have made significant progress but have hit a roadblock that seems to be the final hurdle. The button component in my library is successfully exported, a ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

Guide to parsing HTML tables using JavaScript

I have a set of HTML tables generated from a pandas data frame in the following format: list_html = [<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>score</th> &l ...

What is the best way to make the SPA load with the tab displaying the highest value?

I have a React single-page application using Typescript and Material UI. One challenge I'm facing is creating a tab menu with the current month and all previous months, where the last month should be active when the page loads. Despite researching on ...

Learning how to merge two observable streams in Angular2 by utilizing RxJS and the powerful .flatMap method

Within my Angular2 app, I have created an Observable in a Service called ContentService. Here is a simplified version of the code: @Injectable() export class ContentService { constructor(private http:Http, private apiService:ApiService) { th ...

What is preventing the route with parameters from functioning properly in Angular2?

I'm currently working on implementing a basic route with a parameter in Angular2. My setup involves Angular 2.0.0-rc.2 and angular router 3.0.0-alpha.7. I've mostly relied on the updated routing documentation available at https://angular.io/docs/ ...

Learn how to add a variable to a PHP array using a jQuery click event

The following button is what we're working with: <button id="animals" type="button" value="push" >Push</button> In my PHP array, I currently have: $animalArray = array($dog, $cat, $horse, $lamb, $fox); Here is the jQuery code snippet t ...