Is it possible to verify that a string exclusively comprises elements from an array?

Hey there, I've got a challenge where I need to verify whether a string consists only of letters from a predefined alphabet. If not, my bot kicks players from the game. I've come up with the following 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");
  }

While this code works for names that don't contain any letters at all, it falls short when dealing with names that contain a mix of valid and invalid characters.

For instance, 𝐏𝐚𝐧𝐝𝐚 would be kicked out, but 𝐏𝐚nda wouldn't because it includes some valid letters from the predefined array. How can I modify this script to account for this scenario and keep players with valid names in the game?

Appreciate any suggestions or solutions you may have!

Answer β„–1

It appears that a straightforward regex solution is available for this issue:

var letters = "abcdefghijklmnopqrstuvwxyz";
var regex = new RegExp("[^" + letters + "]", "i");
var players = ["𝐏𝐚𝐧𝐝𝐚", "𝐏𝐚nda", "Panda"];
players.forEach(player =>
{
  console.log(player, regex.test(player));
});

The main concept is to find and match any characters that are NOT included in the letters

This specific scenario can also be more concise by utilizing [^a-z] instead:

var regex = new RegExp("[^a-z]", "i");
var players = ["𝐏𝐚𝐧𝐝𝐚", "𝐏𝐚nda", "Panda"];
players.forEach(player =>
{
  console.log(player, regex.test(player));
});

P.S. There is no need to separate your alphabet with a space when splitting it.

"abcd".split("")
will achieve the same result

Answer β„–2

Regular expressions (Regex) offer the perfect solution for your needs.

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");
}

Answer β„–3

Try a different approach this time. Utilize the some method to loop through the characters in the name and check if they are included in the letters array.

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 validateLetters(letters, name) {
  const found = [...name].some(letter => letters.includes(letter));
  return found ? `${name}: ok` : `${name}: Your name cannot contain unusual characters`;
}

console.log(validateLetters(letters, '𝐏𝐚𝐧𝐝𝐚'));
console.log(validateLetters(letters, 'Bob'));
console.log(validateLetters(letters, 'BOB'));
console.log(validateLetters(letters, '123'));
console.log(validateLetters(letters, '𝐏𝐚nda'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

Output the result of a PHP script inside a JavaScript code

I'm having trouble getting the code below to display the success word. Can anyone spot what's wrong with it? Appreciate any help in advance. <script type="text/javascript"> function verification(){ var s = document.test_form.textfiel ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

Using the Petite-vue Initialization attribute within an HTML script tag

I came across a snippet of Vue.js code on Twitter from Evan You, but I'm confused about the purpose of the init attribute in the script tag. I've searched on MDN and other sites but couldn't find any information about it. However, I do unde ...

Incorporating a computed variable in a v-select within a VueJs endless loop

I've been attempting to utilize a computed value in a v-select component from Vuetify, but every time I select an item, it triggers an endless loop. To demonstrate the issue, I have recreated my code in this CodePen. Please be cautious as it may caus ...

Ways to reset a JQuery/JavaScript filter

I am currently working on a list of div items that are being filtered and sorted using JavaScript. Each item animates as it enters the screen, scaling up to its final size. However, when I apply filters using buttons, items that are already displayed do n ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

A guide on demonstrating time using the AngularJS date filter

Is it possible to display the time in AM and PM using the angular date filter? I attempted to achieve this with the provided code, however, it did not yield the desired result. <div>{{ '12:31:07' | date:'HH:mm' }}</div> ...

What's the best way to add a timestamp and class name to Angular's $log for an enhanced logging experience?

Is there a way to customize Angular logs by adding a timestamp and classname? For example: $log.info('this log entry came from FooBar'); "9:37:18 pm, FooBar: this log entry came from FooBar" I've come across various examples online that ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button? Below is the code snippet I have been working on, but it only r ...

How can I show a tooltip when hovering over a tab using uib-tab?

Currently facing an issue with HTML/Bootstrap. My tabs are displayed using the uib-tabset directive on Angular Bootstrap (UI Bootstrap). I am trying to implement a tooltip that appears when hovering over a tab that is disabled. Does anyone know how I can a ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...

Javascript-generated HTML is malfunctioning as sliders are failing to slide

Currently learning Javascript and jQuery as I work on a one-page site using fullPage.js with data fetched from WordPress via JSON. The end goal is to convert this single-page site into a mobile app using cordova. Challenges: Utilizing the right/left slid ...

Understanding JavaScript for Reading a Website's "Local Storage"

Can the local storage of one website be accessed by a different domain, or is it restricted to only the domain that saved it? ...

The Material-ui Drawer element is failing to display its internal items

In my current project, I am building a practice e-commerce application utilizing React.js, @material-ui/core/Drawer, and Redux. I've encountered an issue where manually rendering items to the Drawer works fine, but utilizing a handleAddToCart function ...