+ 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??😐😐😐
6 odpowiedzi
+ 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!")
}
+ 2
Simple contains is not an option for you? Otherwise you'd have to define the substring as a pattern and then match it.
+ 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 🙃
+ 1
Sandra Meyer that approach checks for the existence of the whole substr.....
+ 1
Thanks Russ, this' what I needed!
+ 1
Great! 😀