JS replace all characters equal

Posted on

Question :

I’m trying to use the replace function to turn a letter into 0, however this does not work when I want to test the letter inside a var.

var palavra = "abelha";
var letra = 'A';
palavra = palavra.replace(/(letra)/g, '0');

Any solution?


Answer :

You can use new RegExp(padrĂ£o, flags) , but you must use the i flag also to ignore case sensitive (not case sensitive):

var palavra = "abelha";
var letra = 'A';
var re = new RegExp(letra, 'gi');
palavra = palavra.replace(re, '0');



Leave a Reply

Your email address will not be published. Required fields are marked *