Danish Flag Fixer explainer

The aim of this puzzle: Use the .replace() function to fix a mistake in a string.

Walkthrough of the solution: On line 1, the variable flag contains the string 'rwrr wbww rwrr'. On line 2, this string will be used as an argument for the drawBoxes() function.

The flag of Denmark has 2 colors: red with a white cross. Unfortunately, the ‘b’ in ‘rwrr wbww rwrr’ means that DrawBoxes() will mistakenly put a blue box in the flag. We can use the .replace() function to fix this mistake. Inside the drawBoxes() function, .replace() is added to the end of flag. This function will look for a target string inside flag, and replace it with a new string.

Inside the parentheses, .replace() takes 2 arguments, the target string 'b', and the replacement string 'w'. When the code runs, .replace() will find the 'b' in 'rwrr wbww rwrr, and replace it with a 'w'. Then drawBoxes() will draw the correct flag of Denmark.

It is important to note that the .replace() function will only replace the first match it finds. If the string contained two 'b's, only the first (farthest left) would be replaced. This post explains how one could “replace all”.

Sample code solution:
(Tap below to reveal)

var flag = 'rwrr wbww rwrr';
drawBoxes(flag.replace('b', 'w'));

Javascript Concepts: Variables, Strings, .replace()

Grasshopper Concepts: drawBoxes()

My code was this but I think this should have been accepted.

Hey there, you only need to use var when you’re declaring a new variable. When you’re changing the value of an existing variable, you can leave it out.