Basic Algorithm Scripting: Mutations resolved using Regular Expressions

Basic Algorithm Scripting: Mutations resolved using Regular Expressions
0

#1

I’m trying to resolve the Basic Algorithm Scripting: Mutations resolved using Regular Expressions, but I keep getting an error and I can understand why.

First the task:

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

My solution:

function mutation(arr) {
let str1 = arr[0].toString();
let str2 = arr[1].toString();
let testRgex = /[str2]/i;

return testRgex.test(str1);

}

mutation([“hello”, “hello”]);
mutation([“Alien”, “line”]);

Every test is working except this two.

This is the error:
// running tests

mutation([“hello”, “Hello”]) should return true.

mutation([“Alien”, “line”]) should return true.

// tests completed


#2

“Alien” does not contain the string “line”, that’s why it’s false. Your code is testing that. “Hello” does contain the string “hello” if you of ore case, so that is true.


#4

Edit: ah crap I just edited and overwrote my post instead of adding a new post, sorry

“Alien” contains all the letters in “line”, but it does not contain the characters in the same order.


#5

but this line let testRgex = /[str2]/i; does not test for characters?
if it will be let testRgex = /str2/i it will test for string.

Am I right?


#6

for example, if I test :

mutation([“Mary”, “Aarmy”])
mutation([“zyxwvutsrqponmlkjihgfedcba”, “qrstu”])

the test is true

but when I check:

mutation([“hello”, “Hello”]) it fails to return true.


#7

Regex is a tool specifically designed to find patterns in strings, it’s not general purpose - it’s not really for checking if some values appear in an arbitrary order in a collection of values: you can do hacking around to make it work, but that’s not its purpose

You specify a pattern of charaters using the syntax, and you can then check if that pattern appears in another string.

The pattern “these letters in any order, also the target string I’m checking could have those letters anywhere in it”, that’s not a simple thing, regex is not the correct tool here, especially the way you’re trying to apply it.

If str2 is “line”, or “hello”, or “dsfjkhadfklhad”, this isn’t going to make a difference:

/str2/i

Is saying ‘look for a sequence of characters that exactly matches “str2”, ignoring case’

/[str2]/i

Is saying ‘find one character that matches “s”, “t”, “r” or “2”’ (the brackets are saying ‘one of whatever is in them’).

To pass in variables, you need to build the Regex:

const regex = new RegExp(str2, 'i');

This still isn’t going to help you much beyond comparisons where things are in the right order (‘Hello’ and ‘hello’ for example)


#8

Thanks for your answer. I’ll try a different approach.