How can I prevent my "translator" from trying to replace, for example, the word keyboard
like it was the words key
and board
and the word treehouse
like it was tree
and house
?
I added some white spaces when calling the function to prevent it but what I need is to have something around the variable string
when creating the RegExp so it checks for spaces without replacing them.
(function() {
let variable = 'Something. Treehouse bla bla keyboard bla - The End';
function replace(string, replacement) {
const pattern = new RegExp(string, 'gi');
variable = variable.replace(pattern, function(match) {
if(match.charAt(0) === match.charAt(0).toLowerCase()) {
return replacement;
} else {
return replacement.charAt(0).toUpperCase() + replacement.slice(1);
}
});
}
replace(' board', ' prancha');
replace(' house', ' casa');
replace('key ', 'chave ');
replace('keyboard', 'teclado');
replace('tree ', 'árvore ');
replace('treehouse', 'casa na árvore');
console.log(variable);
})();