Skip to content
Advertisement

How can I make a variable the name of an element from firebase and alter the new variable?

I’m working on a drive thru app project that uses firebase and JavaScript to display the menu information. I planned to use a template text for displaying everything and it all worked fine. I was even able to make a variable = the value of a field in firebase, but I’m unable to alter that new value. I wanted to replace all spaces with underscores since that is how I named the pictures in my project but it seems to just ignore this command. Here is the code:

let itemName = menuItem.name;
itemName.replace(" ", "_");
console.log(itemName);

Does anyone know of a solution to this?

Advertisement

Answer

Javascript’s String.prototype.replace function doesn’t edit strings in-place, it creates a new one. As well, when doing simple string replacement, it only replaces the first instance – you want replaceAll. This code will do what you want:

let itemName = menuItem.name;
let newName = itemName.replaceAll(" ", "_");
console.log(newName);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement