Check if every single string within an array exists within another string using Javascript and return true if they all do

Trying to determine if a variable contains all the strings from an array has proven trickier than expected. I've attempted various methods, but they all seem overly complex and unsuccessful. Any suggestions would be greatly appreciated.

For example:

var myArray = ["cat","dog","bird"];
var myString = "There is a cat looking the bird and a dog looking the cat";
var myString2 = "There is a cat and a dog looking one each other";

myArray and myString should return true, while myArray and myString2 should return false.

I've been experimenting with something like this:

var selector = "dir.class#id";
var code = '<div id="id" class="class"></div>';
var tokens = selector.split(/[\.,#]+/);

for (var i = tokens.length - 1; i >= 0; i--) {
    var counter = [];
    if (code.indexOf(tokens[0]) > -1 ) {
        counter.concat(true);
    }
}

Thank you!

Answer №1

To achieve this, you can use the following code snippet:

const checkWordsInText = function (text, words) {
    return words.every(function(word){
        return text.includes(word);
    });
}

console.log(checkWordsInText(sampleText, sampleArray)); //outputs true
console.log(checkWordsInText(anotherText, sampleArray)); //outputs false

Answer №2

Here's a working example:

 let animals = ["cat", "dog", "bird", "cat"];
 let sentence1 = "There is a cat looking at the bird and a dog looking at the cat";
 let sentence2 = "There is a cat and a dog looking at each other";

 function checkAnimals(arr, str) {
    let count = 0;
    for(let i in arr){
        let value = arr[i];
        if(str.indexOf(value) !== -1) count++;
    }

    return (arr.length === count);
 }

 console.log(checkAnimals(animals, sentence1));

Answer №3

function ensureContainString(array, target){
for(index in array){
    if(target.indexOf(array[index]) == -1)
     return false;
}
 return true;
} 

Answer №4

Give this code snippet a shot:

const checkArrayElementsInString = (array, string) => {
  for(let index = 0; index < array.length; index++){
    if(string.indexOf(array[index]) === -1){
      return false;
    }
  }
  return true;
}

Answer №5

If you're looking to find matches at the end of words without requiring them to be at the beginning, your best bet is to utilize a regular expression or some other form of processing.

Using indexOf will match the character sequence anywhere within the word, not just at the end. To target strings that appear at the end or as whole words, consider the code snippet below:

    var myArray = ["cat","dog","bird"];
    var myString = "There is a cat looking the bird and a dog looking the cat";
    var myString2 = "There is a cat and a dog looking one each other";
    var myString3 = "There is a classcat and a iddog looking at bird";
    var myString4 = "There is a catclass and a dog looking at bird";

    document.write(myArray.every(function(word) {
      return (new RegExp('\\w*' + word + '\\b').test(myString));
    }) + '<br>');
    document.write(myArray.every(function(word) {
      return (new RegExp('\\w*' + word + '\\b').test(myString2));
    }) + '<br>');
    document.write(myArray.every(function(word) {
      return (new RegExp('\\w*' + word + '\\b').test(myString3));
    }) + '<br>');
    document.write(myArray.every(function(word) {
      return (new RegExp('\\w*' + word + '\\b').test(myString4));
    }));

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

When copying text from React-PDF Display, the values may appear altered or varied

This snippet of text was excerpted from a brief SHA provided at the git summit. Generated using React-pdf, this is a PDF document with some interesting quirks. Although the displayed text reads as 4903677, it changes to •G07THH when copied. The font ...

Tracking page views through ajax requests on Google Analytics

I have implemented a method to log page views through ajax action when the inner page content is loaded. However, I am facing an issue where the bounce rate data is not getting updated and always shows 0%. The default Google Analytics page view is logged ...

What is the reason that filter_input does not work for retrieving form data when $_GET functions without any issues?

Currently, I am utilizing the get method along with a form to save the status of checkboxes into an array. I have made an effort to utilize a filter_input line to grab details from each checkbox one by one and store it in an array. Everything seems to wor ...

Creating dynamic queries in Node.js and MongoDB by combining both constants and variables

I am faced with a situation where I need to create a field name dynamically using a variable and some constants. While I know how to use just the variable to form the field name. var index = parseInt(req.body.index); db.collection("user_data").update( { ...

submitting numerous forms using AJAX

On my webpage, each entry in the database has its own form that saves data upon pressing the enter key. However, I am facing an issue where only one specific form is being saved and not all of them. How can I differentiate between the forms and ensure that ...

Generate an array that maps values to their corresponding indexes in the original array

Consider the following 2D array: map = [[0, 1, 1], [0, 2, 1], [0, 2, 2]] The goal is to create an array of indexes based on the values in the array. For instance, if map[0][0] == 0, then the pair (0, 0) should be at index 0 in the result array. The desir ...

The speed of the jQuery mouse scroll script remains constant and cannot be altered

I've been searching online... I attempted to adjust the scrolling settings on my website but nothing seems to be working. Does anyone have a guide or list of mouse scroll jQuery scripts and functions? (I've cleared caches, performed cross-brow ...

One-Of-A-Kind Typescript Singleton Featuring the Execute Method

Is it feasible to create a singleton or regular instance that requires calling a specific method? For instance: logger.instance().setup({ logs: true }); OR new logger(); logger.setup({ logs: true }); If attempting to call the logger without chaining the ...

To ensure that the spied function is not called, be sure to use Jest's spyOn function

As per my notes from Jest: Note: By default, jest.spyOn also triggers the spied method. Within my Angular component. ngAfterViewInit(): void { this.offsetPopoverPosition(); } In my spec: it('Expect ngAfterViewInit() to call offsetPopoverPosition ...

ajax ignores output from php

I've been working on passing PHP echo values through AJAX, but I've encountered a problem where the if and else conditions are being skipped in the success function of AJAX. Even when the if condition is met, the else statements are still being e ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

Sorting names in C using arraysWould you help in sorting names in C

I am seeking guidance on how to sort names in an array. I am struggling with sorting and printing it out in my C programming project as I am a beginner. Any advice would be greatly appreciated (apologies for any language errors). Thank you. https://i.sst ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

How can we eliminate duplicate objects in a JavaScript array by comparing their object keys?

I am trying to remove duplicate objects from an Array. For example, the object 'bison' appears twice. var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ...

React-router version 6 now supports breadcrumbs and partially matching routes

Currently, I am utilizing react-router-dom v6.8.1 (the most recent version at the moment) and had previously implemented a breadcrumb system that was functioning well with a third-party library called use-react-router-breadcrumbs. However, as per their doc ...

Using a 2D array of classes with constructor invocation in the C++ programming language

I'm facing an issue where I have a class and I need to create a two-dimensional array of that class. Typically, I would use vectors for this task, but unfortunately, the library I'm working with doesn't support that. This made me realize tha ...

Which items have the capability to activate the key press event within the DOM?

I've been conducting some tests and it appears that only form elements and the window object are able to activate the keypress event. I've referred to the MDN documentation and the spec, but I couldn't find a definitive list of the valid ob ...

Identifying page elements in Protractor when they lack obvious identifiable properties

Scenario Here is the HTML code snippet using an Angular JS template: <div class="data-handler-container"> <div class="row"> <div class="data-handler" ng-if="dataController.showDistance()"> <p>{{ 'Item ...

The error message "ERR_CONNECTION_TIMED_OUT when trying to access Google APIs fonts

Upon deploying my web project on the client server, I encountered an error and noticed slow page loading. GET https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic net::ERR_CONNECTION_TIMED_OUT The browser ...

navigating a pointer graphic within a container

I've been working on creating a sniper game, but I've run into an issue with moving the sniper image inside the div. My main objective is to change the image to the sniper image when the mouse hovers over the div. Here's what I have tried so ...