Can a string starting with certain values be omitted?

How can I determine if a value begins with any of the values in an array?

var value = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

if (checkForStartsWith(value, excludeItems)) {
    // Exclude the value
}

Answer №1

Make sure to check if any of the elements in the array successfully pass a test with the startsWith method on the string:

var value1 = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

const v1excluded = excludeItems.some(str => value1.startsWith(str));
const v2excluded = excludeItems.some(str => value2.startsWith(str));

console.log(v1excluded, v2excluded);

In this specific scenario, as a string starting with -- will also definitely start with -, you can opt to omit the -- from the excludeItems array altogether.

If your excludeItems is predetermined and there are numerous characters to assess, employing a regular expression and character set might offer a more concise solution:

var value1 = "background-color";
var value2 = "--my-variable";

const excludeItems = /^[-_!@#$%]/;

const v1excluded = excludeItems.test(value1);
const v2excluded = excludeItems.test(value2);

console.log(v1excluded, v2excluded);

Answer №2

In addition to the answer provided by CertainPerformance, you can simplify the code using a one-liner like this:

[value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)))

var value1 = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

const excluded = [value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)));

const included = [value1, value2].filter(val => !excludeItems.some(str => val.startsWith(str)));

console.log(excluded);
console.log(included);

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

Error in parsing JSON: An unexpected token < was encountered at the beginning of the JSON input, causing a SyntaxError at position 0 when parsing with

I need to transfer an array from a PHP file to JavaScript and save it in a JavaScript array. Below is the snippet of JavaScript code: xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 ...

What is the best way to determine the file size using Node.js?

My current challenge involves using multer for uploading images and documents with a restriction on file size, specifically limiting uploads to files under 2MB. I have attempted to find the size of the file or document using the code below, but it is not p ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

Original state of class name is restored upon change

I'm currently working on creating a Lightbox-style effect using CSS and Javascript. The idea is to change the classname of an element (OverlayContainer) to toggle between a normal background and a darker overlay. However, I've run into an issue w ...

Creating a method in Angular that combines async/await functionality with Observables

After transitioning from using async/await to Observables in Angular, I am trying to refactor the following code snippet to make it work with Observables: async refreshToken() { const headers = this.authStorage.getRequestHeader(); const body = { ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? https://i.sstatic.net/jjogP.png <TextField variant="outlined" label="Quantity" onChan ...

Using JavaScript to extract information from a dropdown menu

Currently, I am working on a project that involves reading values from a dropdown box on a webpage and alerting the selected value. Below is the code I have written for this task. JavaScript function main(input) { value = getValue(); alert(value) ...

Is the conditional module require within an "If" statement always executed in nuxt.config.js?

Despite the missing file mod.json, the "require" statement is still executed leading to an error. The condition should have prevented it from entering the "if" block: const a = 1; if(a === 2){ const mod = require('./scripts/mod ...

In JavaScript or Typescript, using the return statement within the .then callback function nested inside the

Looking to filter an array, but it requires calling the database which returns a promise. Here's the code: this.arrayToFilter.filter(myObject => { this.dataBaseService.getSomething(myObject.id).then(something => { // performing som ...

Update the content within a document and implement jQuery to make it clickable

Within my webpage, there is a random occurrence of the word -FORM-. I am looking to replace this word with another text that includes dashes for creating a clickable div. Despite having some code that successfully replaces the text, it lacks the function ...

Concealing a label for a certain range of values

Does anyone have a clever solution for dynamically hiding a label associated with an input range element when the value is below a certain threshold? And then reappearing it once the value surpasses a specific minimum? Any thoughts on this matter? Thank ...

Transforming Node's loops into asynchronous functions

I have the following sync function: for (var i = 0; i < results.length; i++) { var key1 = results[i]['__key']; for (var j = i + 1; j < results.length; j++) { ...

What is the best way to adjust the size of an SVG path when zooming in Highcharts?

Recently, I developed a module that allows users to draw an svg line over a highchart using the Renderer. However, I encountered an issue where the size and position of the drawn line remain static when the user zooms into the highchart. It is essentia ...

Constructing an interactive table from a JSON dataset using Node.js and Express

Just starting out with Node.JS here! I'm currently working on creating a page with multiple tables and information using NodeJS. However, I've hit a roadblock when trying to display the result of an SQL query in an HTML table. Right now, I'm ...

I've been attempting to adjust the currentTime of an HTML5 video element within a React JS environment, but for some reason it keeps reverting

Need help updating the currentTime of an HTML5 video element with a slider in React JS. My issue is that whenever I adjust the slider, the value resets to 0. The problem seems to be related to the handleChange function which updates the videoRef.current.cu ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Tips for setting up cookie-based authentication in a SvelteKit and MongoDB environment

I am looking to integrate cookie authentication into my SvelteKit & MongoDB application. Specifically, I want to understand how to effectively utilize hooks, endpoints, set up a database connection, and showcase this functionality within a template proje ...

The table disappears when there is no data available in the database

One of my challenges involves a table that displays data retrieved from a database. The code for this is as follows: <table class="table table-hover table-bordered" style="width:300px" id="contact"> <tbody data-bind="foreach:items"> ...

Clickable label for checkbox in Android browser is unresponsive

I've been experimenting with creating a responsive CSS menu using the checkbox hack Here's the HTML: <input type="checkbox" id="button" /> <label for="button" onclick>click / touch</label> <div> Change my color! </d ...

Transferring information from one webpage to another using AJAX or embedding it with an iframe

I recently received an address with a basic HTML structure containing numbers. I attempted to display it using an iframe, which worked when tested separately but encountered a connection refusal error when embedded in my page. Alternatively, I tried AJAX ...