0

why below code is not replacing {0}

var errorMessage = "Minimum {0} and maximum {1} characters allowed",spec =[1,60], dRegex;
   for(i = 0; i<2; i++){
      
      dRegex = new RegExp("\\{"+i+"\\}","g");
      errorMessage.replace(dRegex,spec[i]);
    }
"Minimum {0} and maximum 60 characters allowed"

nikunj
  • 132
  • 1
  • 6
  • 2
    The `.replace()` method returns the new string with replacements. It does not change the original string. – Pointy Aug 23 '21 at 15:29
  • 3
    Questions like these can very often be answered by consulting documentation from MDN or some other reliable source. (There are in fact many similar questions about `.replace()` on this site.) – Pointy Aug 23 '21 at 15:30

2 Answers2

3

You need to set errorMessage. replace doesn't modify the string. It returns the modified string.

var errorMessage = "Minimum {0} and maximum {1} characters allowed",spec =[1,60], dRegex;
   for(i = 0; i<2; i++){
      
      dRegex = new RegExp("\\{"+i+"\\}","g");
      errorMessage = errorMessage.replace(dRegex,spec[i]);
    }
console.log(errorMessage)
Ayaz
  • 2,111
  • 4
  • 13
  • 16
1

Answer is already given (strings are immutable, so you have to reassign the value of a replace operation).

Alternatively, you may want to explore template literals

const specs = [1, 60];
const errorMessage = `Minimum ${specs[0]} and maximum ${
  specs[1]} characters allowed`;
console.log(errorMessage);

// or replace immediately
console.log(
  "Minimum {0} and maximum {1} characters"
    .replace(/\{(\d+)\}/g, (a, b) => specs[b])
);
KooiInc
  • 119,216
  • 31
  • 141
  • 177