Basic Algorithm Scripting: Mutations using RegEx

Tell us what’s happening:
I would like to solve this test by using RegEx, although I always get these test results. I expected that using pattern /[Hey]/i shouldn’t match the string “hello” because the “y” is not part of the string, but I am a bit confused now…

// running tests
mutation(["hello", "hey"]) should return false.
mutation(["hello", "neo"]) should return false.
mutation(["voodoo", "no"]) should return false.
// tests completed

Your code so far

function mutation(arr) {
  const patt = new RegExp("[" + arr[1] + "]", "i");
  return patt.test(arr[0])

console.log(mutation(["hello", "Hey"]));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:

@rogierv, you need to add ‘g’ flag as well, as now your regex only checks the first character

I believe you are on the right path but maybe doing this backwards.

I know it sounds counter-intuitive but have you considered making your regex from arr[0] and testing that all the letters of arr[1] come from that set?

That by itself won’t give you a working solution but it will get you closer.

1 Like

I’ve added the ‘g’ flag, but that didn’t solve the problem, I received the same test results.

Yes, I’ve considered that and checked it before, but I got the same results as well. Although this brought me on a track to think a bit different. I added a for loop to check each character in arr[1] and tested them to arr[0], and this worked without any problems!

1 Like
function mutation(arr) {
  const pattern = new RegExp('^[' + arr[0] + ']+$', "i");
  return pattern.test(arr[1]);

The trick is to include start and end in your regular expression to eliminate the possibility of any characters other than the character set provided by arr[0].


That is a neat solution!
Although is sometimes hard to grap, especially the end expression +$ is difficult to understand. Did you find this by trial and error? Or is this just basic RegEx knowledge?

I kind of flew through the regular expression part of FCC but retained little so I’m always drawn to these regex forum posts so I can practice and learn. I played with your problem some when I saw your original post. I saw how it could be done but didn’t want to spoil your work in progress or bias you to one possibility.

This is what’s happening

one or more characters  from the set   [...]+
would match "qrstu" but would also match "qrstu222"

between the  ^  beginning and  $  end of string 
nothing else but one or more characters from the set [...]+
which would match "qrstu" but not "qrstu222"

If you are keen to use regular expressions frequently you might consider an online tool like regexr to help you visualize what your expressions actually match. Hovering over just about anything on the page reveals more about what is happening

1 Like