Yo guys, I have an array of the alphabet and I wanna check whether a string only contains the items of this alphabet. If not, my bot kick a player from a game. I managed to write this script:
var letters =
"a b c d e f g h i j k l m n o p q r s t u v w x y z";
var arrayLetters = letters.split(/ +/);
var allLetters = arrayLetters.map((x) => x.toLowerCase());
if (!allLetters.some((x) => player.name.includes(x)) {
room.kickPlayer("Your name can't have strange fonts");
}
Actually, this works but with names that doesn't contain a letter at all.
For example, 𝐏𝐚𝐧𝐝𝐚 would be kicked but 𝐏𝐚nda won't because there are some letters which are part of the array. How can I solve this? I wanna also keep players who only contains those letters in my array.
Thanks so much for the answers!
It sounds like there is a simple regex solution for this:
var letters = "abcdefghijklmnopqrstuvwxyz";
var regex = new RegExp("[^" + letters + "]", "i");
var players = ["𝐏𝐚𝐧𝐝𝐚", "𝐏𝐚nda", "Panda"];
players.forEach(p =>
{
console.log(p, regex.test(p));
});
The basic idea is to match any characters that are NOT part of the letters
This particular case can also be shortned by using [^a-z] instead:
var regex = new RegExp("[^a-z]", "i");
var players = ["𝐏𝐚𝐧𝐝𝐚", "𝐏𝐚nda", "Panda"];
players.forEach(p =>
{
console.log(p, regex.test(p));
});
P.S.
You don't need separate your alphabet with a space in order to split it. "abcd".split("") would do same thing
Regex is the best solution for you.
var letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
var arrayLetters = letters.split(/ +/);
var allLetters = arrayLetters.map((x) => x.toLowerCase());
var regex = new RegExp(`[^${allLetters.join('')}]`, 'i');
if (regex.test(player.name)) {
room.kickPlayer("Your name can't have strange fonts");
}
Do it the other way around. Use some to iterate over the name characters and test to see if they exist in letters.
const letters = 'a b c d e f g h i j k l m n o p q r s t u v w x y z';
function validLetters(letters, name) {
const found = [...name].some(letter => letters.includes(letter));
return found ? `${name}: ok` : `${name}: Your name can\'t have strange fonts`;
}
console.log(validLetters(letters, '𝐏𝐚𝐧𝐝𝐚'));
console.log(validLetters(letters, 'Bob'));
console.log(validLetters(letters, 'BOB'));
console.log(validLetters(letters, '123'));
console.log(validLetters(letters, '𝐏𝐚nda'));