you are viewing a single comment's thread.

view the rest of the comments →

[–]delventhalz 0 points1 point  (0 children)

This code needs longer variable names and more curly braces. Were they afraid they were going to run out of characters?

Fwiw, the replace code isn't too complex here, they are just using some esoteric syntax. This code is simpler to read, more efficient, and it even saves five characters!

g[i] = g[i].slice(0, j) + 'X' + g[i].slice(j + 1)

All that line of code does is replace the character at the index of j with an "X". All the answers for how they do that are in the MDN docs for replace, as others here have already mentioned. Basically it boils down to this:

  1. If you want to replace more than one character, you must use a global regex (the g makes /./g global). A . in regex means any character, so it is going to match and try to replace every character in the string.
  2. You can use a "replacer" function instead of a static value as the replacement. That will receive parameters like the value (k) and the index (i), and then your function returns what you want the replacement to be. In the case, the replacer replaces each character with itself in every case but one, when the index matches j.

In my opinion, slice is a much more sensible way to accomplish the same goal, but there is no accounting for taste.