Binary Agents - maybe a bug?

Hey! So I made this code for the Binary Agents challenge and it looks fine, though for some reason it doesn’t translate the last binary pattern of the second test into an exclamation point. It only does it when I place some other pattern inside the argument.

  let binaryRegex = new RegExp(/\s([01]*)\s/);
  let arr = str.split(binaryRegex);
  console.log(arr);
  let result = []
  arr.forEach((item) => {
    return result.push(String.fromCharCode(parseInt(item, 2)));
  });
  console.log(result);
  let newStr = result.join("");
  console.log(newStr);  
  return newStr;
}

When I test for

binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001");

it prints “I love FreeCodeCamp” (whitout the “!”)

But when I test for

binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001 00100001");

it prints “I love FreeCodeCamp!!” (with 2 “!”).

Could anyone shed some light on this?

for some reason in the first case the last two characters are not splitted resulting in having last item of the array as "01110000 00100001", but the other case they are correctly splitted. Seems a fun mistery, but I can’t purse further now

Maybe you should just split on the space…

1 Like

Yeah, how you’re using split is the problem. The first parameter is supposed to be the “separator”, not the thing you are retrieving. It’s not the binary numbers that are the separators but the spaces. If I fix that, your code passes.

1 Like

Your issue is maybe the number of spaces. In the regex expression you have two space characters, but with your first string you have an odd number of characters causing the last split to not happen.

You may need to remove one of the spaces from there. Or just split on the spaces


@kevinSmith
Today I learned a new thing! Look at the examples, " Splitting with a RegExp to include parts of the separator in the result"

1 Like

Omg you guys, yeah, I don’t know why the hell I wanted to use regex for the split, much easier to just use space. Rofl, thank you!

let binaryRegex = new RegExp(/\s([01]*)\s/);

you can change this; let binaryRegex = new RegExp(/\s+/);

That’s a good point. I didn’t know about that either. But I think that it is overly complicated and will get worse if you try to fix it. Splitting on ' ' is so much simpler and to the point.

Also that is true - I was searching for the reason of the two different behaviours