Ways to determine if a substring is contained within the text of an array item

Recently, I've been researching ways to check if a certain value exists in an array using indexOf('textvalue'). However, I have encountered the issue of my 'textvalue' being a substring, which causes no matches to be found. The problem lies in passing the field name to the method and needing to remove specific text by matching the array item based on "Door". Can anyone suggest a solution for this dilemma?

Below is the sample code I am currently working with:

(spnSelectedDisclosures contains a list of selected fields, and the following code snippet aims to eliminate the previous field selection from the text delimited by semicolons.)

var currentText = $("#spnSelectedDisclosures").text();

var existingArr = currentText.split(";")

for (i=0;i < existingArr.length;i++) {

   var indexItem = " " + existingArr[i].toString(); // I'm confused as to why indexItem remains an object instead of a string. Adding a space was an attempt to convert it into a string variable.

    if (indexItem.contains(substringText)) { // The error occurs here, stating that the object does not have a 'contains' method.
       alert("A match has been found at position: " + i);
       textToRemoveIndex = i;
       break;
    }
  }

 var textToRemove = existingArr[textToRemoveIndex];
 var newText = currentText.replace(textToRemove,""); 
 $("#spnSelectedDisclosures").text(newText); 

Answer №1

Any thoughts on this matter?

for (let i = 0; i < existingArr.length; i++) {
  if (existingArr[i].includes(substringText)) { 
    alert("A match has been found at index: " + i);
    textToRemoveIndex = i;
    break;
  }
}

Answer №2

Support for String.contains() is quite limited:

Cross-browser compatibility

Chrome              Not supported
Firefox (Gecko)     19.0 (19)
Internet Explorer   Not supported
Opera               Not supported
Safari              Not supported

To achieve the desired outcome, consider using a regular expression or indexOf method instead.

if (indexItem.indexOf(substringText)!==-1) {

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 updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...

Interactive JavaScript function designed to react to user commands

Struggling to develop a JavaScript/AngularJS function that notifies the user whether a entered number is too high or low (> 100 indicates it's too high)? Check out the HTML code below: <div> <p id="num">Number : <input type="nu ...

Tips for saving the circular slider value to a variable and showcasing it in the console

I have coded a round slider and need assistance with storing the slider value in a variable and displaying it in the console using JavaScript. I want to store the tooltip value in a variable for future use. $("#slider").roundSlider({ radius: 180, min ...

jQuery is able to retrieve all the table data (TD) elements within a table

Using jQuery, I am extracting data from a table: $('#lc_searchresult > table > tbody > tr').each(function() { var data = $(this).find("td:eq(5)").html(); alert(data); }); It works well when the TR tag contains only one ...

AngularJS Issue: Duplicate Error

Attempting to refresh data after making some changes results in duplicate errors appearing within the ng-repeat. The scenario is as follows; I am working on creating a dynamic menu module The requirements include adding, deleting, changing the order, an ...

What is the correct way to declare this and assign values afterwards? (javascript)

I am having trouble with this code and I can't figure out how to properly declare it. var input = { container: '.slide_container', container_all: '.slide_show', slides: [] }; var $slides = $(&a ...

Filling a HTML div with data through PageMethods and AJAX

My issue is quite unique. Despite checking numerous examples before reaching out here, I am facing a peculiar problem. I have a div element in my ASPX file and I am using AJAX to send a POST request to populate it. <script> function send(input ...

Creating information with PhpExcelTemplator

I am encountering an issue when trying to generate the result enclosed in brackets [] using the export tool provided by alhimik1986/php-excel-templator. $sql = mysqli_query($conn, $qry); $result = mysqli_fetch_array($sql); foreach ($sql as $row) { $ ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

Is there a way to create an infinite fade in/out effect for this?

Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

jquery's each method is not functioning as intended and causing unexpected issues

I'm in the midst of developing a website, and one section requires users to input their details into a form. My goal is as follows: When a user clicks the submit button with any empty fields, I want a span element (initially set to display none in CS ...

`Is it possible to implement the geocode function multiple times within a single post request using npm node-geocoder?`

I've been struggling to develop a function returnCoords(par1) that allows users to input text and convert it to coordinates using the node-geocoder npm. Despite my efforts, the function returns undefined. I attempted to resolve this using async and aw ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

Access the JavaScript array within a click function by dynamically generating the array name

Here's a scenario where I have an array like this: var first_array = ['foo','bar','foobar']; My goal is to run a click function that retrieves the array's name and iterates through its elements. The array has an ID ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

Help needed with jQuery to load a value from a text file and display it in a dropdown menu, then retrieve the user's selection - seeking

Greetings, fellow coders. I'm reaching out to the community for some assistance :) Currently, I have a PHP form with three dropdown menus that utilizes a jQuery function to load .txt files and generate two dynamic dropdown menus based on the selectio ...

What could be causing alloca to repeatedly return duplicate addresses?

Currently, I am working on developing my own math library with a focus on vectors. The approach I am taking involves providing the class with a pointer to an array of numbers, duplicating the array, and storing it in the data address specified by a private ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...