Discovering ways to determine if multiple strings are present within a single string using JavaScript

After writing this function, I noticed it only worked with a single string value.


contains(input, words) {
      let input1 = input.split(' ');
      for (var i = 0; i < input1.length; i++) { 
          if (input1[i] === words) {
              return true;
          } else {
              return false;
          }
      }
}

let contains = Str.prototype.contains('hello me want coffee','hello');

This will return true.

I am now wondering how to modify the function so that it can work with multiple words.


let contains = Str.prototype.contains('hello me want coffe',['hello','want']);

Answer №1

If you want to avoid using the contains() method, consider utilizing the some() method in conjunction with the includes() method:

console.log(['hello', 'want'].some(x => 'hello me want coffe'.includes(x)));
console.log(['hello', 'want'].some(x => 'me want coffe'.includes(x)));
console.log(['hello', 'want'].some(x => 'me coffe'.includes(x)));

Answer №2

To achieve this, you can utilize the some function together with the split method.

let checkContains = (str, words) => str.split(' ').some(element => words.includes(element));
console.log(checkContains('hey there give tea',['give','hello']))

Answer №3

experiment with the indexOf() concept

function checkForWords(input, phrases) {
       total = phrases.length;
    while(total--) {
       if (input.indexOf(phrases[total])!=-1) {
          return true;
       }else{
         return false;
       }  
      }  
     }


console.log(checkForWords('hello there',['hello','there']));

Answer №4

Utilizing the power of RegExp can help you search for specific strings with the added benefit of being case insensitive.

// 'i' signifies that the search is case insensitive
const contains = (str, array) => array.some(x => new RegExp(x, 'i').test(str));

const arr = [
  'hello',
  'want',
];

console.log(contains('hello me want coffe', arr));
console.log(contains('HELLO monsieur!', arr));
console.log(contains('je veux des croissants', arr));

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

Internet Explorer no longer supports SCRIPT tags in AJAX responses

We are currently facing an issue in our project where AJAX returns some code, and we utilize innerHTML to insert this code into a DIV. Subsequently, we scan this DIV for all script tags and execute the contents of these script tags using EVAL() (which add ...

receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements. place locfrnd, which is an array While I was able to successfully access place, I encountered an error when trying to a ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

What are some strategies to reduce the frequency of API calls even when a webpage is reloaded?

Imagine I'm utilizing a complimentary API service that has a restriction of c calls per m minutes. My website consists of a simple HTML file with some JavaScript code like the one below: $(function () { //some code function getSomething() { ...

Exploring the process of retrieving outcomes from Node.js within a Knockout ObservableArray

Below is the Node.js code snippet I have: var http = require('http'); var port = process.env.port || 1337; var MovieDB = require('moviedb')('API KEY'); MovieDB.searchMovie({ query: 'Alien' }, function (err, res) { ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

What could be causing my AngularJS controller to fail in my jasmine test?

I encountered the following error message: "Controller: MainCtrl should retrieve a list of users and assign to scope.users FAILED TypeError: 'undefined' is not a function (evaluating 'Users.findAll()') at /Users/John/NetBea ...

Access information through token-based verification

Just starting out in this area of development, a colleague shared some information with me on how to retrieve the database. I'm feeling a bit lost as to what to do next. curl -X GET -H "Authorization: Token token=xxxxxxxxxxxxxxxxxxxxxxxxx" "https://w ...

Breaking down an object containing an internal array and omitting specific keys

I've got this specific object structure: const objBefore: { "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1", "number": "5000", "enabled": true, "classes": [ { ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Efficiently sift through a vast assortment using a filtering method

Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude). One specific requirement is to find drivers who are within a 200-meter distance from the user& ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...