verifying that all characters in an array are permissible

Can someone explain why this code always returns false even when I enter "abcdef" into the prompt, which should make it return true?

var userinput = prompt('Enter characters:');

var lowercase = userinput.toLowerCase();

var allowedcharacters = ["a", "b", "c", "d", "e", "f"]

function match(input, statement) {
    for (var i = 0; i < statement.length; i++) {
        if (input.indexOf(statement[i]) == -1) {
            return false;
        }
    }
    return true;
}

if (lowercase == allowedcharacters){
  alert(true);
}
else{
  alert(false);
}

Answer №1

Take a look at the complete code snippet. By reviewing this, you can gain some insights. Cheers!

Answer №2

Make sure to include the match function in your code. Consider this alternative approach:

if (match(letters, allowedchars)){
  alert("Valid");
}
else{
  alert("Invalid");
}

UPDATE As requested, a modified version of the match function to validate absence of disallowed characters:

function noForbiddenChars(input, forbidden) {
    for (var j = 0; j < forbidden.length; j++) {
        if (input.indexOf(forbidden[j]) >= 0) {
            return false;
        }
    }
    return true;
}

Answer №3

It appears that the match function you created is not being utilized.

Answer №4

let userInput = prompt('Enter characters:');

let lowerInput = userInput.toLowerCase();

let alphabet = ["a", "b", "c", "d", "e", "f"];

if (checkMatch(lowerInput, alphabet)) {
  alert(true);
} else {
  alert(false);
}

function checkMatch(input, chars) {
    for (let i = 0; i < chars.length; i++) {
        if (input.indexOf(chars[i]) == -1) {
            return false;
        }
    }
    return true;
}

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

Tips for running a function in CodeBehind triggered by jQuery?

In my Aspx code, I have the following: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebSite.View.Index" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

Utilizing a JavaScript variable to fetch a rails URL: A comprehensive guide

One interesting feature I have is an image link that has a unique appearance: <a href="#user-image-modal" data-toggle="modal" data-id="<%= image.id %>"><img class="user-photo" src="<%= image.picture.medium.url %>" alt="" /></a&g ...

The prop type `cellHeight` provided to `GridList` in (Material-ui / React) is invalid

warning.js:33 Warning: The prop type for cellHeight in the GridList component is invalid. I encountered this error message, despite the property functioning correctly. Is there a way to resolve this issue? If you're interested, check out the documen ...

What steps should be taken in PHP to display a popup when the user input is found to be invalid?

I've been working on implementing a popup in PHP to show if the user enters an existing username, as per our teacher's requirement to use popUp instead of alert. I have set the visibility property of the popup to "Hidden" in CSS; <div class=&q ...

Troubleshooting a ThreeJS Issue: the Mystery of the Malfunction

I have a ribbon showcasing various thumbnails. These thumbnails are painted on a canvas and then added to a Texture. var texture = new THREE.Texture(textureCanvas); The mesh is generated as shown below loader.load('mesh_blender.js', functi ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

The result of filtering multiple data using checkboxes in Vuetify is not displaying as expected

I am currently working on developing a straightforward task scheduler that includes filtering options using checkboxes. Below is the snippet from my vue file: Within my templates section, <fieldset> <legend>TASK STATUS</legend> ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

Preventing a scroll handler from executing once an element has been clicked

When a user scrolls to the video, it will automatically start playing. Similarly, when the user scrolls away from the video, it will stop playing and display the poster image. However, I encountered an issue where I don't want this functionality to tr ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Save information in a session using html and javascript

I'm having trouble accessing a session variable in my javascript code. I attempted to retrieve it directly but ran into issues. As an alternative, I tried storing the value in a hidden HTML input element, but I am unsure of how to properly do that wit ...

The directive attribute in AngularJS fails to connect to the directive scope

I have been attempting to pass an argument to a directive through element attributes as shown in the snippet below: directive app.directive('bgFluct', function(){ var _ = {}; _.scope = { data: "@ngData" } _.link = function(scope, el ...

Error: Unable to locate font in the VueJS build

Within my config/index.js file, I have the following setup: ... build: { index: path.resolve(__dirname, 'dist/client.html'), assetsRoot: path.resolve(__dirname, 'dist'), assetsSubDirectory: 'static', assetsPub ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

What is the best way to toggle buttons on and off with jQuery?

I've recently started a project for my class, and as a complete beginner in this field, I'm facing some challenges. My server is running on Ubuntu. In script.js, the following code is included: $(document).ready(function(){ $.get('/var/ ...

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...