+ 2

[SOLVED]How can I test if a string contains some characters [that are in a variable] without a specified order?

I want to check if individual values[all] of a string exist in another string. E.g str = "sololearn" substr = "lnoe" // the test should confirm that str contains substr // Is it possible with regex??😐😐😐

23rd Jun 2020, 6:19 AM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
6 Answers
+ 3
Clunky wouldn't even begin to describe the following code. The theory is to create a lookahead for every single character of substr. This would be much easier if you know substr in advance, but this is what I've come up with for when you don't. let string = "sololearn"; let substr = "lnoe"; let regex = ""; for (char of substr) { regex += `(?=.*?${char})`; } regex = new RegExp(regex); if (string.match(regex)) { console.log("Yes!") } else { console.log("No!") }
23rd Jun 2020, 8:43 PM
Russ
Russ - avatar
+ 2
Simple contains is not an option for you? Otherwise you'd have to define the substring as a pattern and then match it.
23rd Jun 2020, 2:16 PM
Sandra Meyer
Sandra Meyer - avatar
+ 2
I don't think it's possible to check the existence of all characters from a given substring in another string independent from their order. Therefore I would create an array of characters from the substring and check each entry in a loop. But maybe here's a regex master who knows a solution 🙃
23rd Jun 2020, 5:39 PM
Sandra Meyer
Sandra Meyer - avatar
+ 1
Sandra Meyer that approach checks for the existence of the whole substr.....
23rd Jun 2020, 5:34 PM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
+ 1
Thanks Russ, this' what I needed!
23rd Jun 2020, 8:59 PM
asɥɐ🔹ʞɐɹnnƃı
asɥɐ🔹ʞɐɹnnƃı - avatar
+ 1
Great! 😀
23rd Jun 2020, 9:15 PM
Russ
Russ - avatar