Substitute terms in a sentence according to the guidelines

Looking to transform strings based on specific rules?

"Hello {{firstName}}, this is {{senderName}}."

Consider the following rules:

rules = {
  firstName: "Alex",
  senderName: "Tracy"
}

The expected output would be:

"Hello Alex, this is Tracy."

If you need a versatile function to automate this process for any string and set of rules, look no further.

Take for instance:

let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
rules = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
expectedResult = "Hello Alex James, this is Tracy."

Your assistance in achieving this task would be highly valued.

Answer №1

One way to dynamically replace variables with their corresponding values in a string is by looping through the rules object and using the replace method.


function resolveVariables(rules, str){
  for(let key in rules){
    str = str.replace("{{"+key+"}}", rules[key]);
  }
  return str;
}

let message = "Hello {{firstName}} {{lastName}}, this is {{senderName}}.";
const rules = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
};

console.log(resolveVariables(rules, message));

Answer №2

To enhance your code, consider utilizing a replacement function that can be utilized with String.prototype.replace:

const str = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
const mapping = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
const compile = (template, rules) => template.replace(/{{(.+?)}}/g, (match, group) => rules[group]);

const result = compile(str, mapping);
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

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Having trouble converting the response into a valid TypeScript value for storage

These are the interfaces I have described: enum ProductType {current, closed, coming} export interface CurrentProductForCarousel { type_product:ProductType.current; offers: ProductMainInfo[] } export interface ProductMainInfo { id: number; disclai ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my m ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Can a decorator be added to a Typescript class after it has been created?

Is it possible to update a class with inversify's @injectable decorator after it has been created? My use case involves using a mocking library like ts-auto-mock to generate a mock for me, and then applying the @injectable decorator to bind the mock t ...

Implementing TypeScript in React FlatList

While TypeScript is a powerful tool, sometimes it feels like I'm working more for TypeScript than it's working for me at the moment. I'm currently using a FlatList to display restaurant results in a Carousel. const renderRestaurantRows = ( ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

What is the process of extracting information from a JSON file and how do I convert the Date object for data retrieval?

export interface post { id: number; title: string; published: boolean; flagged: string; updatedAt: Date; } ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...

Using optional function arguments with destructured arguments in TypeScript can result in throwing an error

interface Type1 { attr1: string; attr2: string; } interface Type2 { attr1: string; attr2: string; attr3: string; // additional attribute } function fn(config: Type1 | Type2): void { // The error code is displayed above. I am ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to e ...

How Vue3 enables components to share props

Having recently made the switch from Vue2 to Vue3, I find myself a bit perplexed about the best approach for sharing props among multiple components. My goal is to create input components that can share common props such as "type", "name", and so on. Previ ...