Breaking up conditions in Javascript

Let's take a look at some variables:

var available_options = 'Option A|Option B|Option C|Option D';
var selected_option = 'Option A';

I am interested in using conditionals within functions like this

function checkOption(sel, avail){
 var options = avail.split('|');

 /* Insert desired code here */

 if(sel === options[0] || sel === options[1] || sel === options[2] || sel === options[3])
 {
  alert('Success!');
 }
}

This function can be called as follows

checkOption(selected_option, available_options);

Answer №1

It seems like you're looking for the indexOf method:

function findElement(collection, item){
 var array = item.split('|');

 if(~array.indexOf(item)) { // array includes item as one of its elements
  alert('Success');
 }
}

Answer №2

Utilize the .indexOf method to search within an array:

var countries_list = 'United States|Germany|Canada|United Kingdom';
var user_country = 'United States';

countries_array = countries_list.split('|'); //Split by |
alert(countries_array.indexOf(user_country)); //Find the index of the user's country in the countries_array.

Implementation as a function:

function checkCountry(current, list) {
    var array = list.split('|');
    if (array.indexOf(current) != -1) {
        alert('Found it!');
    }
}

Answer №3

Why is this so complicated?

function dummy(c, p){
  var arr = p.split('|');
  for (var i in arr)
    if (arr[i]===c)
      alert("OK");
  alert("KO");
}

Answer №4

When you maintain the pipe bar at the end

var possible_country = 'United States|Germany|Canada|United Kingdom|';

You will only require a single line for checking:

if (possible_country.indexOf(current_country + '|') > -1)
{
    alert('Success!');
}

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

Rendering on the server side using Material UI 1 in combination with Node.js and React

Issue: Unable to load styles initially through server-side rendering. Despite following the documentation, the styleSheets variable remains empty. In my Navigation component, I utilize JSS and withStyles. According to the documentation, using withStyles s ...

What is the process for retrieving data from a website?

Currently, I am in the process of setting up an automated test using the basic page object pattern. The objective is to open Google, input a search query, click on a link from the results, and retrieve the information. So far, I have successfully navigated ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

Clicking on the search box will remove the item that is currently displayed

Currently, I am working on creating a dropdown menu that includes a text box. The goal is for the items to appear when the text box is clicked, and for the selected item to turn green once clicked and then display in the text box. I'm interested in fi ...

Retrieving the data from an HTML button with JavaScript

Currently, I am working on creating a calculator. The HTML and CSS components are complete, but I am facing an issue with getting the button clicks to reflect in the display. As I am still new to JavaScript, I would appreciate any guidance on how to achiev ...

How to Retrieve a Targeted Element from a Multidimensional Array

I've got some data that looks like this: [[12, 23],[27,-6],[52, -32],[82, 11]] How can I access specific elements within these arrays? With a standard array like this: [a, b, c, d] It's easy to reference 'b' as arrayName[1]. But ho ...

Removing Content with React

I attempted to remove the item, but when I click on the button the function does not work! Deleting in the backend is functional, however it does not work in the frontend! This is the delete function: deleteblog = async id => { // this.setSta ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Incorporating Layouts and Partials in Handlebars Template

Can you provide guidance on incorporating layouts and partials with handlebars templates like the example below? I have reviewed the documentation on partials but am still struggling to achieve my desired outcome. default.html The default layout is util ...

Exploring Tooltips in Three.js

Is there a way to implement tooltips in Three.js elements like spheres when hovering over them? I am working with a 3D scatter plot and I would like a tooltip to appear every time the mouse hovers over one of the spheres in the plot. Is it possible to cr ...

Problem encountered during JSON parsing in JavaScript causing loss of the "id" field

Upon parsing this string using JSON.parse(), I noticed that some objects contain id = null. However, upon inspection, I am unable to find any object with id = null. Is there a potential issue here? console.log("TERRITORIES000: "); ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

JavaScript in fullscreen mode for Internet Explorer

I'm trying to make sure that this code snippet... $('#gatewayDimmer').width($('html').width()); $('#gatewayDimmer').height($('html').height()); $('#gatewayDimmer').css('display','block& ...

Developing dynamic objects for input string fields in AngularJS

In my AngularJS view, I have the following setup: <label class="control-label">Name:</label> <input type="text" class="form-control" ng-model="config.name" /> <br /> <label class="control-label">versionSpecificApiConfig:&l ...

Enhance your HTML audio player with added timeline functionality

I'm currently working on incorporating an HTML audio player into my project. I've managed to get the play/pause functionality to work, but now I'm stuck on adding a timeline feature. Additionally, I'm not sure how to implement the play/ ...

Is it possible for Node.js to manipulate video files?

I'm curious about the compatibility of Node.js with videos, specifically in terms of editing rather than just playing them. My ultimate goal is to be able to reverse videos online. While Java seems like a solid option so far, I am drawn to Node.js for ...

Tips for extracting specific field titles from a RESTful API with the help of ExpressJS and Axios

Recently, I have been working on some code that allows me to retrieve data from an external API. Below is an example of the code: //endpoint to fetch data from an external API app.get("/externalapi", (req, res) => { let apiURL = &apos ...

Issue with Laravel 5.6 and Vue.js: Bootstrap 3.3.7 dropdown malfunctioning

I am currently utilizing laravel 5.6, vuejs, and Bootstrap 3.3.7 in my project. However, I encountered an issue where adding the file app.js caused my dropdown functionality to stop working, prompting a requirement for popper.js. Upon including popper.js ...

Issue: ReactJS + MaterialUI + TypeScript - Property 'component' does not exist?Possible error in ReactJS: component property is

Currently, I am designing my own custom typography. However, I have encountered an error while implementing it. I have been referring to the following documentation: https://mui.com/material-ui/api/typography/ Here is the code snippet that I am using: h ...