Find a partial match in the regular expression

I am currently working on filtering a list of names using regular expressions (regex).

The data is stored in the following format:

[
 {
  "firstName": "Jhon",
  "lastName": "Doe",
 },
 ...
]

Users have the option to enter either a full name, first name, or last name. However, it is crucial for me to match all variations. My mongo query is structured like this (I utilized Loopback 4 to construct this query, but the concept remains clear)

        {
          or: [{firstName: new RegExp(searchKey, 'i')}, {lastName: new RegExp(searchKey, 'i')}],
        };

Unfortunately, this method does not successfully match when a user enters "jhon doe", yet it does work if only a first or last name is provided.

This leads me to my inquiry: Is there a way to match part of a string against a regex?

The desired outcome is to achieve a successful match for "jhon", "doe", "jhon doe", and "jhondoe".

Answer №1

Creating a universal regex for this task may not be feasible, so I opted to develop a brute force algorithm instead.

let text = `[
    {
     "firstName": "Jhon",
     "lastName": "Doe",
    },
    ...
   ]`;

// Brute force
let key = "jhondoe";
let keyArr = [];
for (let i = 0; i < key.length; i++) {
    let a = key.slice(0, i);
    let b = key.slice(i);
    a && keyArr.push(a);
    b && keyArr.push(b);
}
let keySearch = keyArr.join("|");
console.error(keySearch);
let regex = new RegExp(`"(?:first|last)Name": "(${keySearch})"`, `gim`);
let matches = text.match(regex);
console.log(matches);

Answer №2

In my latest code iteration, I have implemented a comprehensive solution that takes multiple factors into consideration. However, there is still a flaw where the code accepts names like "jhon doe" and "jhond oe" as valid.

The core concept behind this code is to determine whether the input key corresponds to either the first name or the last name. If the key contains spaces, it separates the first name before the space and the last name after the space. Alternatively, through brute force, it explores all possible combinations of first and last names by splitting the string into substrings.

let text = `[
    {
     "firstName": "Jhon",
     "lastName": "Doe",
    },
    ...
   ]`;

const nameValidator = (key, text) => {
  // Check if the entire key represents a first or last name.
  let regexKey = new RegExp(`"(?:first|last)Name": "${key}"`, `gim`);
  if (regexKey.test(text)) {
    return true;
  } else if (key.includes(" ")) {
    // Extract first and last name when key contains spaces
    let [_, a, b] = /^(\w+) (.*)$/.exec(key);
    let regexFirstLastName = new RegExp(`"firstName": "${a}",(\\s|\\t|\\n)*"lastName": "${b}",`, `gim`);
    if (regexFirstLastName.test(text)) {
      return true;
    }
  } else {
    // Brute force search for first and last name division
    for (let i = 1; i < key.length; i++) {
      let a = key.slice(0, i);
      let b = key.slice(i);
      console.log(`Trying name="${a}" and lastname="${b}"`);
      let regexFirstLastName = new RegExp(`"firstName": "${a}",(\\s|\\t|\\n)*"lastName": "${b}",`, `gim`);
      if (regexFirstLastName.test(text)) {
        return true;
      }
    }
  }
  return false;
}

const keys = ["jhon", "doe", "jhon doe", "jhondoe", "auehuaheuahe"];

for (key of keys) {
  console.log(key, nameValidator(key, text));
  console.log("=======================\n");
}

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

Tips for including a subquery in query results using axis

I have a query for the objects table using an id. Then, I want to query the same table with the id from my result and add it as a new property. Does that explanation make sense? app.get(`/details`, (req, res) => { const { id } = req.query; connectio ...

What causes AJAX to disrupt plugins?

I am facing a challenge with my webpage that utilizes AJAX calls to load content dynamically. Unfortunately, some plugins are encountering issues when loaded asynchronously through AJAX. I have attempted to reload the JavaScript files associated with the ...

Execute JavaScript code via URL injection

One interesting aspect of the HTML is that it has a feature where it opens a webpage. The specific webpage it opens is determined by the URL, for example: https://mywebsite.com/index.html&audio=disabled In addition to this, there is a useful JavaScri ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

Troubleshooting Vue 3 Computed Property Not Updating

I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this: <button ...

What is the most effective method for establishing functions in AngularJS?

Hey there, I'm currently working on a function in AngularJS and I'm not sure what the best practice is for defining methods. Any suggestions would be greatly appreciated. Option 1: var getBranchKey = function(currentBranchName) { }; Option 2: ...

The error message UnhandledPromiseRejectionWarning: TypeError: crypto.subtle.digest is throwing an error as it is

Encountering an error message saying "crypto.subtle.digest is not a function" when running unit tests using Jest for a function that utilizes crypto.subtle.digest(), have attempted to resolve the issue while using JSDOM with no success: 1. `[Utilizing J ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Generate fresh input fields with distinct identifiers using JavaScript

My challenge is to dynamically create new empty text boxes in JavaScript, each with a unique name, while retaining the text entered in the previous box. I struggled with this for a while and eventually resorted to using PHP, but this resulted in unnecessar ...

Information backed by the HTML5 Local Storage feature

Is it possible to use a Local Storage object to store another Local Storage object? Thank you in advance. ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Matching the items within an HTML unordered list with PHP's regular expressions

Imagine a scenario where a webpage contains multiple unordered lists - how can we extract the elements from just one list using PHP regex? <html> <head> <title>A title</title> </head> <body> <ul id="list1"> <l ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

Angular Sending JSON Data via POST Request

Whenever I submit an empty form through my Angular application, the JSON being sent is as follows: {foo: {}} This causes a 500 error to occur on my server instead of the expected 422 error, since the server requires the following structure: {foo: {bar: ...

Leveraging a specific section of an HTML5 CSS3 Bootstrap template in a separate template

As I create my website using a combination of free templates, I often find myself needing to merge elements from different designs. One specific example is wanting to incorporate the "Client Logo Slider" component from template 2 into my original template. ...

Having trouble with my getJSON function, can't pinpoint the error in my code

After collaborating with some fellow stack users, I have developed the following: http://jsfiddle.net/9ywLq/ I am looking to integrate an external json file in order to achieve something similar to this: http://jsfiddle.net/RCB9M/ Currently, I am linki ...

Conceal a child div through the use of AJAX technology

Utilizing AJAX, I am loading pages on my website. Each page consists of two common div elements - the header div and the content div. When navigating from one page to another, I load the content div of the next page into the current page using the followin ...

Want to learn how to create an image magnifier using just one image?

At first, I created an image magnifier that would zoom in when the user hovered over the image. However, now I am looking to switch to a lens zooming method that uses only one image. ...