Using Regular Expressions in JavaScript to verify if an element from an array is contained within a string

Looking for a simple JavaScript code for a Vue application that will split the string into an array and check if any value is present in a different string.

Here's what I have:

              let AffiliationString = " This person goes to Stony Brook"

              let affiliation = "Stony Brook OR Stony Brook University OR The University of Washington"
              let affiliations = affiliation.toLowerCase().split(" or ");
              affiliation = affiliations.join(",");
               let regexList = [ affiliation ];

               let isMatch = regexList.some(rx => rx.test(AffiliationString));

I am trying to determine if any item in the array is found in the "AffiliationString" string.

When attempting this, I encounter the following error:

       Uncaught (in promise) TypeError: rx.test is not a function

I have explored various examples on StackOverflow demonstrating how to check if a value exists in an array, but not the reverse. I am referencing: javascript - match regular expression against the array of items

This task is being carried out within a Vue project utilizing:

         "eslint": "6.7.2",

Should I approach this by looping through each value in the array?

Thank you for your assistance.

Answer №1

It appears that you are not correctly creating RegExp objects from your affiliation string, leading to the error where rx.test is not recognized as a function. To resolve this issue, consider constructing a single RegExp pattern that covers all possible affiliation strings by separating them with the | operator. Each element within the regex should be enclosed in \b to avoid partial matches (e.g., ensuring "Brook" does not match "Brooktown"). Additionally, including the i flag in the RegExp declaration will make it case-insensitive:

let AffiliationString = " This person goes to Stony Brook"
let affiliation = "Stony Brook OR Stony Brook University OR The University of Washington"
let regex = new RegExp('\\b' + affiliation.split(/\s+or\s+/i).join('\\b|\\b') + '\\b', 'i')
let isMatch = regex.test(AffiliationString)
console.log(isMatch)

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

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

AngularJS withCredentials Issue causing data not to be transmitted

When using AngularJS, I encountered an issue where the cookie/session was not being shared across domains for my Restful API in a subdomain. To address this problem in Angular, I added the following configuration: app.config(['$httpProvider', fu ...

Initiate an ajax request only when there are pre-existing ajax requests in the queue

Setting up the Form I've created a form that utilizes checkboxes to determine a selected number on a page: When a checkbox is selected, it triggers a call to a controller that saves the selection and returns the updated total quantity based on its c ...

Managing actions with IconMenu and ListItem in React using MaterialUi

Currently, I am delving into the world of React and attempting to create a simple TODO list using Material-UI. However, I have encountered an issue with handling IconMenu menu actions within a listItem element. I am struggling with triggering the deleteI ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Generate a fresh array of elements and combine the objects that share the same value

Looking to create a new array of objects based on the original specs array of objects. I have searched for similar questions but nothing has solved my issue. const specs = [ { label: 'Brand', value: 'Nike' }, { label: 'Age ra ...

Using Vue.js to set and retrieve changes on a range slider with v-model

Currently, I am in the process of adding a slider feature to my web form, allowing users to input their desired rating for a specific item. https://i.sstatic.net/e2a6L.png Utilizing Vue.js for this task, I am seeking guidance on how to properly configure ...

Is there a way to sequentially load two iframes, with the second one loading only after the first one is fully loaded

Having two different links that trigger ajax calls can be tricky if only one request is allowed per load. This may result in both iframes displaying the same data. Is there a way to work around this issue? Perhaps loading one iframe first and then triggeri ...

Trouble with downloading files using the anchor (a) tag in React

Every time I try to click on the a tag to download the file named approved_leads.zip, I keep receiving an error message saying "failed - no file". It seems like the path is correct, so I'm not sure what is causing the issue. <a href="../../ass ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Executing functions in real-time using React Native

I'm fairly new to Object-Oriented Programming (OOP) and my understanding of promises, asynchronous/synchronous function execution is quite basic. Any guidance or help from your end would be greatly appreciated! Let's take a look at an example fr ...

`an error occurs when trying to loop through an object and add a key``

I'm currently facing an issue with adding a key to an object through looping. Here is the code snippet: function checkResult(want, reference) { const keys = Object.keys(reference); for(let i=0; i<Object.keys(reference).length; i++){ console ...

Revamp responsiveness in bootstrap 3 for printing with @media queries

My goal is to disable the responsive features of bootstrap when the event javascript:print() is triggered. This way, I want my webpage to maintain the column grid layout that I have defined, regardless of screen size. One solution suggested in this answer ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

The default selection in res.format is not being properly recognized

When I make a request with the accept header set as "application/json, text/javascript, */*; q=0.01", the response is always in HTML format instead of the default format specified. It seems like something is missing here. Given that the header does not spe ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...