.test what it does is verify that your pattern is matched at least once, it stops there.
For example if your pattern is a set of characters [abcLpeEr]
and your source string is "aloha"
your code will stop at the first “a” and return true because a set of characters in regex what it does is assert that ANY character of the list is present.
What you want is a way to verify that ALL the characters from the 2nd argument are present in the string from the 1st argument.You COULD do it with RegExp (I know because I did it) but you have to know a little bit of set theory and the .match
method of the String prototype.
Why? Because even if you were to extract all the characters that match your regex, you still need to:
1- Get rid of the duplicates
2- Consider that the match should be case-insensitve (a = A, e = E and so on)
3- Compare lengths of unique lowercase letters in set B vs the length of the matched unique lowercase letters from set A.
What you can do instead to do some sort of obscure ninja art is use positive lookaheads which is kind of an advanced topic:
A little example
^(?=.*H)(?=.*e)(?=.*l)(?=.*l)(?=.*o).*$
Remember that ^ means start of the line, $ means end of the line, the dot (.) character is a wildcard that means any character and * is for zero or unlimited amount of matches. (?=) is a capturing group with a positive look-ahead that means that whatever is behind should be followed by the next lookaheads; you can specify as many as you like together which kinda form a chained AND operator??? I didn’t understand why when I read it on the regex spec but at least I know that it works lol.
lexiheplWOzniaK
matched against the aforementioned case-insensitive pattern yields:
index |
match |
sub-pattern |
0 |
^ followed by l
|
(?=.*l)(?=.*l) |
1 |
^l followed by e
|
(?=.*e) |
2 |
^lexi followed by H
|
(?=.*H) |
3 |
^lexih followed by e
|
(?=.*e) |
4 |
^lexihep followed by l
|
(?=.*l)(?=.*l) |
5 |
^lexiheplW followed by O
|
(?=.*o) |
6 |
zniaK$ after all of the previous |
.*$ |
If one of the lookaheads were to fail, then the whole thing fails. So in order to construct the whole regex you’d have to do:
const pattern = new RegExp(
'^' +
args[1]
.split('')
.map(char => `(?=.*${char})`)
.join('') +
'.*$'
, 'im')
And now the whole function:
function mutation(arr) {
const pattern = new RegExp(
'^' +
arr[1]
.split('')
.map(char => `(?=.*${char})`)
.join('') +
'.*$'
, 'im')
return pattern.test(arr[0]);
}