- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find specific words in an array with JavaScript?
To find specific words in an array, you can use includes(). We have the following array −
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
Now, the following is an array having the words we need to search in the above “sentence” array −
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
Example
Following is the code −
var keywords = ["John", "AUS", "JavaScript", "Hockey"]; var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"]; const matched = []; for (var index = 0; index < sentence.length; index++) { for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) { if (sentence[index].includes(keywords[outerIndex])) { matched.push(keywords[outerIndex]); } } } console.log("The matched keywords are=="); console.log(matched);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo226.js.
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo226.js The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]
Advertisements