Locate individual characters within a string and append the entire word to an array upon discovery

Given an array and a string, how can we push whole words that contain the word 'WORD' into the array?

var arr = [];
var str='This is mWORDy word docuWORDment';

if (str.indexOf('WORD') > -1) {
  arr.push(Whole word here)
}

Although the current code works, we aim to modify it so that we achieve this result:

arr['mWORDy','docuWORDment'];

How can we accomplish this task efficiently?

Answer №1

To break up a sentence into individual words and apply filtering to an array, you can utilize the split method along with filter. You can also use the includes method to determine if a string contains a specific word.

var str = 'This is mWORDy word docuWORDment';
var arr = str.split(" ").filter(o => o.includes("WORD"));

console.log(arr);

Answer №2

To demonstrate the usage of String.prototype.match() method with a basic regular expression:

const sentence = 'This is an EXAMPLE example string';
const matches = sentence.match(/\w*(EXAMPLE)\w*/g);

console.log(matches);

Answer №3

This regular expression can be utilized to identify and extract specific word patterns surrounded by word boundaries, storing them in an array for further processing.

const pattern = /\b([A-Za-z]+WORD[A-Za-z]+)\b/gm;
const str = `This is mWORDy word docuWORDment`;
let m;

let matchedArr = [];

while ((m = pattern.exec(str)) !== null) {
  // Add the matched group to the array
  matchedArr.push(m[1]);
}

console.log(matchedArr);

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

Retrieve the information from the database associated with a chosen selection and display it in individual form fields

I have a form that includes a select element. The options within the select are dynamically populated from a database. The columns in the database table include: id, date, title, body. Within the select, only the date and title are displayed. Additional ...

Having trouble compiling for IOS using a bare Expo app? You may encounter an error message that reads "Build input file cannot be found."

Encountering Error When Running react-native run-ios on Bare Expo App I am experiencing an issue while trying to run the 'react-native run-ios' command on my Bare expo app. The error message I am receiving is: "Build input file cannot be found: ...

Update your Selenium WebDriver Manager using npm

When attempting to update the selenium webdriver using the "webdriver-manager", an error occurred: Error: Got error Error: read ECONNRESET from https://selenium-release.storage.googleapis.com/2.48/selenium-server-standalone-2.48.2.jar Error: Got error Err ...

Steps for effectively deleting browsing history on Ionic

While testing my app on Chrome browser, I encountered an issue with clearing old views and cache. This is the process I followed to sign out of my app: https://i.stack.imgur.com/EGgRx.png Upon clicking Log out, the following code is executed: Auth.$s ...

Implementing Click-Activated Scroll-to-Div Feature in React

I need to implement a scroll-to-div feature in my React App. However, the current structure of my app is preventing me from passing refs as props correctly, making it challenging to utilize ref.current.scrollIntoView(). The layout of my code looks like th ...

I'm curious about the purpose of the "^=" operator in this algorithm for finding the unpaired numbers. What exactly does it do?

I came across a fascinating code snippet that helps find a unique number in a list of duplicate numbers (where each number appears twice, except for one). function findNonPaired(listOfNumbers) { let nonPairedNumber = 0 listOfNumbers.forEach((n) => ...

What could be causing NVM (for Windows) to malfunction and consistently display error messages every time it is executed?

After attempting to install nvm on my Windows system using https://github.com/coreybutler/nvm-windows, I encountered an error message when running the nvm-setup. Despite reinstalling nvm, resetting the PATH environment variable, and trying to install vers ...

jQuery - checkboxes behaving like radio buttons

I want to create a group of checkboxes that act like radio buttons, allowing only one selection from the group. Each checkbox will have a different name attribute. How can I achieve this behavior? Solution This feature is important for maintaining consi ...

Ways to retrieve multiple outcomes in mongoose and merge them into a unified response

When making an API call in Node.js using Mongoose, I want to execute 3 different queries and then combine the results to create a JSON response. Query student .countDocuments({}) .then(studentNumber => { return studentNumber; }) teacher . ...

Display a list of errors from an array in JavaScript or jQuery, and output them into a designated <

I need assistance with displaying a list of error messages in a specific div. Within my code, I have a #error-list div and an array called errors that contains various error messages: var errors = ["First name is blank", "Last name is blank", "Company na ...

I am facing a problem with the API routes in my Next.js project as the req.query object is coming up as undefined

Issue: I'm facing a problem with accessing query parameters in my API route. Despite sending the correct URL with the query parameter, req.query is returning undefined data instead of the expected values. Here's the Request Handling Code: impor ...

Is it possible for an HTML number input's arrows to change in increments that are different from its designated step attribute?

Within my design, I have implemented an <input type="number" step="1"> element for selecting font size. However, in the context of working on a large canvas, adjusting the number by 1 is hardly noticeable. It would greatly enhance ...

Issues with the functionality of the AngularJS button directive

Currently, I am working on developing a RESTful API utilizing Angular and NodeJS. However, I have encountered an issue where a button to navigate to the details page of my application is unresponsive. While I believe the button itself is correctly coded, I ...

Determine if the input text includes a URL when a key is pressed using jQuery

I am currently working on a feature to detect URLs when users input content manually, paste a link, or a combination of both. My goal is to retrieve the contents of the URL, similar to how Facebook handles it, when the first detection occurs. Here is the ...

Issue in three.js r71 with sprite not following cursor movement

I am having an issue where the sprite is visible when I move the cursor, but it is not moving correctly along with the cursor point. It seems to be moving in the opposite direction. Can someone provide assistance? sprite1.position.set( event.clientX *(- ...

Obtaining JSON data through Ajax following a MySQL query

In the process of setting up my bookshop, I decided to create a cashdesk script. This form includes an ajax dynamic search feature and is specifically designed for use on a local PC, rather than being published on the web. By scanning the EAN code, the fo ...

Replacing text using regex results in whitespace

How can I eliminate text and spaces? For instance: http://www.exampleweb.com/myprogram.rar http://www.examplebackup.com/mybackups.rar http://www.exampleweb.com/myprogram1.rar I have used something similar to remove the second line: http://www.exampleba ...

Chrome version 83 encounters an issue preventing file uploads

I recently updated my Chrome browser to version 83 and encountered some issues with certain forms that utilize an "Ajax upload" component. Despite researching the problems associated with this new version (https://developers.google.com/web/updates/2020/05/ ...

Creating a clickable cell within a table utilizing an Angular directive

Looking for someone with experience in AngularJS directives and jQuery to help me out. I have a simple table displayed and I want users to be able to select any cell by clicking on it, and then navigate using the keyboard. Any ideas on how to achieve thi ...

From mongoose to swagger: "<field>" validation error - BSONTypeError: The argument provided must be a string containing either 12 bytes or 24 hexadecimal characters

I'm currently working on developing a REST API using Express, Mongoose, and Swagger for API documentation. To automate the process of converting my existing schema to Swagger, I utilized the mongoose-to-swagger package. However, I encountered an issue ...