0

I would like to know how I can do to replace exactly every element of a string with another.

Use replace as is proper, but if I send a complete line of a certain character, only the first one replaces me.

example:

let e = "________1", y;

y = e.replace("_","0");

console.log(y);

2 Answers2

1

Use regex and the global (g) flag:

const pattern = /_/g;
const e = '________1';
const y = e.replace(pattern, '0');

console.log(y);
samanime
  • 25,408
  • 15
  • 90
  • 139
1

You need to use a regular expression in the "find" argument so that you can specify the "Global Find & Replace" flag (g). (Scroll down to the "Advanced searching with flags" section of the link I included to read about g.)

let e = "________1", y;

y = e.replace(/_/g,"0"); // Regular expression is delimited by / and /

console.log(y);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71