Using regular expressions to identify sentences containing a list of stopwords

In order to locate sentences that might include a series of stopwords mixed within the phrase to_match, such as:

  • make wish
  • make a wish
  • make the a wish
let stopword: string[]= ["of", "the", "a"];
let to_match : string = "make wish";
let text: string = "make wish wish make a wish wish wish make the a wish make";

I am able to only identify make wish by utilizing this regex:

const regex = new RegExp(`(?:\\b)$to_match(?:\\b)`, "gi"); 

I am curious if there is a way to achieve something like

let to_match_splitted: string[] = to_match.split(" ");
const regex = `(?:\\b)${to_match_splitted[0]}\s(${any(stopword)}?)+\s${to_match_splited[1]}(?:\\b)`;

Where any(stopword) represents a method to match any stopword within the stopword list.

This regex should be capable of functioning regardless of the length of to_match_splitted, including one or multiple stopwords appearing between each string within the list.

Answer №1

If you want to create a regular expression, you can use something like this:

/\bmake(?:\s+(?:of|the|a))*\s+wish\b/gi

For a detailed example, check out the regex demo. Explanation:

  • \b - represents a word boundary
  • make - the word "make"
  • (?:\s+(?:of|the|a))* - indicates 0 or more occurrences of
    • \s+ - 1 or more whitespaces
    • (?:of|the|a) - any of the words "of", "the", or "a" (you can also use an? to match "an" as well)
  • \s+ - 1 or more whitespaces
  • wish - the word "wish"
  • \b - a word boundary

If you want to implement this in your code, you can use the following:

let stopword: string[]= ["of", "the", "a"];
let to_match : string = "make wish";
let text: string = "make wish wish make a wish wish wish make the a wish make";
const regex = new RegExp(`\\b${to_match.split(/\s+/).join("(?:\\s+(?:" + stopword.join("|") + "))*\\s+")}\\b`, "gi"); 
console.log(text.match(regex));

For an interactive demo, you can visit this online demo

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

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

When a textarea contains a new line, it will automatically add an additional row and expand the size of the textarea

Developed a form with the functionality to move placeholders in a textarea upwards when clicked. The goal is to increment the height of the textarea by 1 row for every line break. However, I am uncertain about what to include in the if statement of my Ja ...

Ways to dynamically update button properties in Angular 2

Customized Template, <div *ngFor="let item of items" class = "col-sm-12 nopadding"> <a class="button buttonaquacss button-mini button-aqua text-right pull-right" [ngClass]="{activec: isActive}" (click)='updateStatus(item)& ...

Issue with the compatibility of the datepicker and autocomplete features in jQuery

Separately, the code below works on different PHP pages. However, when combining them on one page, nothing seems to work. In Firebug, the error message reads: TypeError: $(...).datepicker is not a function $("#test1").datepicker({ DATEPICKER CODE & ...

One method for routing pages in React Router is to have a shared component that is displayed on multiple pages, as well as a

My app.js consists of multiple pages with the navbar and sidebar as components, but my login page is different and does not include these elements. How can I use react-router to create separate routes for the login page without the sidebar and navbar, whil ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Populate the ListBox based on the value of the input control in the onKeyUp event

I have a ListBox control <asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem Value="1" Text="XYZ" /> <asp:ListItem Value="0" Text="XYZD" /> <as ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

What is the method to include Raw HTML within the SerializeObject() of a JsonConvert?

I am attempting to replicate the below JavaScript code using Newtonsoft's parser: var nav = { container: $('.ux-navigation-control'), manual: true, validate: true }; My attempt to utilize Html.Raw within Newtonsoft looks like this: var na ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Issue with loading Babel preset in a monorepo setup

I'm working with a monorepo setup using Lerna and it's structured as follows: monorepo |-- server |-- package1 |-- package2 All packages in the repo make use of Babel. After installing all 3 projects, yarn copied all the required @babe ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

What is the best way to clear all input data that has been displayed in every input field within a React js application?

import React, { useState } from "react"; import axios, { Axios } from "axios"; import { ContainerDiv, InnerDiv, StyledButton, StyledInput, } from "./StyledComponents"; function WeatherCard() { const [input, SetInput ...

When the condition within the click function is met, concatenate the variable

I'm currently working on a function that involves adding "http://" to the variable 'bar' if it's not already included. This modified 'bar' value will then be sent via ajax to be inserted into the database and also displayed ba ...

Update the html() function to include any content that has been typed into a

I have a webpage structured like this: <div id="report_content"> Some information <textarea name="personal"></textarea> <b>Other information</b> <textarea name="work"></textarea> </div> Whe ...

Using JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...