Hi @Xavier_Reynolds and welcome to the community
You are right in your feeling that different variables can’t have the same name. So what is going on here?
It is always the same variable which we are updating on every line. After replacing a substring the replace
function returns the updated string. For a better understanding we could rename the variables:
let newStoryWithUpdate1 = newStory.replace(':insertx:', xItem);
let newStoryWithUpdate2 = newStoryWithUpdate1.replace(':inserty:', yItem);
let newStoryWithUpdate3 = newStoryWithUpdate2.replace(':insertz:', zItem);
let newStoryWithUpdate4 = newStoryWithUpdate3.replace(':insertx:', xItem);
/* After the replacements we reassign the updated string to the original variable */
let newStory = newStoryWithUpdate4;
Since replace
returns the updated string you could also chain all four replace
functions. This version isn’t very readable though:
let newStory = newStory.replace(':insertx:', xItem).replace(':inserty:', yItem).replace(':insertz:', zItem).replace(':insertx:', xItem);
For your second question:
When using replace
with just a simple string to be replaced, it will only replace the first match. Since we have two :insertx:
in our story we need to call replace
twice. To do a global search and replace a regular expression has to be used. (This is a rather complicated topic so I wouldn’t bother for now.)
As a general note:
Learning a programming language is sometimes hard but very satisfying when it finally ‘clicks’. I think it is a great idea to read others code and trying to understand it
If you have any other questions I’m happy to help
Have a nice day!
Michael