-1

I have this string

content = 'Hi John Doe,

Your appointment has been scheduled for 30-Mar-20 at 05:00 pm.  
Please confirm your appointment. [link]'

confirmationTagsArray = [
  {tag : '[customer_name]' : value : 'John Doe'},
  {tag : '[startDate]' : value : '30-Mar-20'},
  {tag : '[start_time]' : value : '05:00 pm'},
];

Here is my function to replace strings

  parseBackConfirmationText() {
   let str = this.content;
   this.confirmationTagsArray.forEach(tag => {
     if (str.includes(tag.value)) {
      str.replace(tag.value, tag.tag);
     }
   });
   return str;
  }

In this function i am replacing some strings with another strings in a loop. But it's not replacing the strings. It returns me the same string that i provided like this

Hi John Doe,

Your appointment has been scheduled for 30-Mar-20 at 05:00 pm.  
Please confirm your appointment. [link]

But it should return like this

Hi [customer_name],

Your appointment has been scheduled for [start_date] at [start_time].  
Please confirm your appointment. [link]

What am i doing wrong?

Fahad Hassan
  • 781
  • 10
  • 20

1 Answers1

1

You have few issues in your code:

  1. Your object is syntactically invalid.
  2. You have to declare the function with function keyword.
  3. replace() does not modify the the original string, you have to reassign the modified string to the variable.

Try the following way:

content = `Hi John Doe,

Your appointment has been scheduled for 30-Mar-20 at 05:00 pm.  
Please confirm your appointment. [link]`

confirmationTagsArray = [
  {tag : '[customer_name]', value : 'John Doe'},
  {tag : '[startDate]', value : '30-Mar-20'},
  {tag : '[start_time]', value : '05:00 pm'},
];

function parseBackConfirmationText() {
 let str = content;
 confirmationTagsArray.forEach(tag => {
   if (str.includes(tag.value)) {
    str = str.replace(tag.value, tag.tag);
   }
 });
 return str;
}
console.log(parseBackConfirmationText());
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    I am using angular so no need of declare function with function keyword. Anyway your answer helped me out. Thanx. – Fahad Hassan Mar 30 '20 at 12:27