JS replace all characters equal

3

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?

    
asked by anonymous 17.06.2018 / 22:16

1 answer

5

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

console.log(palavra);
    
17.06.2018 / 22:32