-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?

2
  • Please create a small demo for this and post in your queestion. Commented Mar 30, 2020 at 12:11
  • 1
    str.replace(tag.value, tag.tag); should be str = str.replace(tag.value, tag.tag); Commented Mar 30, 2020 at 12:12

1 Answer 1

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());

Sign up to request clarification or add additional context in comments.

1 Comment

I am using angular so no need of declare function with function keyword. Anyway your answer helped me out. Thanx.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.