Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one.

Still unable to crack it though...

Here's what I need:

Have a JS array that needs to be filtered. The array looks like:

[ 'Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW' ]

For example: All of these inputs should match the first entry ("Gurken halbiert 2kg"):

  • "Gu ha"
  • "gur h"
  • "gu halbi"

The following inputs should not match:

  • "ken halbi"
  • "urk ha"
  • "gur biert"

Why? Because letters at the beginning of any word are missing.

More examples and the entries they should match:

  • input: "Gur" -> matches 1st and 3rd entry
  • input: "Kar g 5" -> matches 2nd
  • input: "G r" -> matches 3rd

In need of help understanding this regex puzzle - it's all chaos to me. Any assistance is greatly appreciated!

Answer №1

When dealing with varying input, it becomes necessary to dynamically generate the regular expression.

In the following function, we are essentially constructing a string and then using new RegExp(string, 'i') to create the regular expression.

The pattern of the expression begins with a caret, followed by:

^[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*

Note that \w* is appended after each input string, and \s+ is if it's not the last input string (meaning, not the end).

function generateRegex (input) {
  var string = '^', arr = input.trim().split(' ');
  arr.forEach(function (chars, i) {
    string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
  });

  return new RegExp(string, 'i');
}

You can then utilize the .filter() method on your array to retrieve the matching elements:

var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
  return value.match(generateRegex('Gur Ha'));
});

Result:

'Gur Ha' finds a match: ["Gurken halbiert 2kg"]

'Gur' finds matches:

["Gurken halbiert 2kg", "Gurken RW"]

'Kar g 5' finds a match: ["Karotten geschnitten 5kg"]

'G r' finds a match: ["Gurken RW"]


Example:

function generateRegex (input) {
  var string = '^', arr = input.trim().split(' ');
  arr.forEach(function (chars, i) {
    string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
  });

  return new RegExp(string, 'i');
}

var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
  return value.match(generateRegex('Gur'));
});

document.body.textContent = JSON.stringify(filteredArray);

Answer №2

Here is an illustration of how to properly screen user input.

Important Points

  • It's crucial to escape regular expression characters in the user input pattern (always sanitize user input).
  • Avoid using "\w" to accommodate special characters like "é".
  • Ensure support for white space characters other than <space>, such as <tab>, which can be inadvertently entered into user input fields causing confusion.

function doSubmit() {
  // Retrieve the user input search pattern string 
  var userInput = document.getElementById("myinput").value,

    // List of strings to search
    testList = [
      'Halved cucumbers, 2kg',
      'Sliced carrots, 5kg',
      'Cucumbers RW'
    ],

    // Between each "word," we allow zero or more non-space characters "[^\s]*"
    // Aka, any extra characters that the user might not have specified in their search pattern are accounted for by this regex.
    // This is then followed by one or more white-space characters "\s+"
    // To address any spacing between the "words."
     // Note that backslashes are escaped here.
    regexBetween = '[^\\s]*\\s+',

    // Match at the start of the string "^"
    // Optionally allowing one or more "words" at the beginning
    // This covers a "word" followed by a space multiple times.
  
   regexString = userInput.trim()
       
       // Escape any potentially problematic characters in a regular expression
       // Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
       .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
       
       // Split into an array of "words"
       .split(/\s+/)
       
       // Combine the "words" to construct our regular expression string
       .join(regexBetween),
     
    // Generate the regular expression from the constructed string (non-case-sensitive 'i')
    
   regexObject = new RegExp(regexStart + regexString, 'i'),
   
    // Filter the input array by checking for matches against the regular expression.
    resultsList = testList.filter(function(item) {
      return regexObject.test(item);
    });

  // Display the array in the results text area, one item per line.
  document.getElementById('output').value = resultsList.join('\n') + '\n===the end===';
}
<form id="myform" onsubmit="doSubmit(); return false;">
  <input type="text" id="myinput" value="" />
  <input type="submit" name="submit" />
</form>
<textarea id="output" rows="5" cols="30">

</textarea>

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 modifying a user's tags with Quickblox's JavaScript SDK

Is there a way to update a user's tags using the Quickblox JavaScript SDK? I have attempted using the parameter names listed below: user_tags tags with var params = { user_tags: ["testing"] }; Kindly avoid suggesting alternatives like "custom ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...

Single input results in array output

I have a pair of items in this array list. $.each(data.recalls,function(i) { var recall = data.recalls[i].nnaId; var description = data.recalls[i].remedyDescription; console.log(recall); console.log(description); $('textarea[name= ...

Browsing HTML Documents with the Click of a Button

After collecting JSON data from a SharePoint list, I am currently in the process of creating an HTML Document. At this point, I have completed approximately 80% of the expected outcome. Due to Cross-Origin Resource Sharing (CORS) restrictions, I have hard ...

Elevate to Babel 7: Unable to access the property 'bindings' of null

I recently made the switch to Babel 7 (upgrading from version 6) using the following commands: npm remove babel-cli npm install --save-dev @babel/cli @babel/core @babel/preset-env This is the content of my .babelrc file: { "presets": ["env"] } After th ...

Can you explain the distinction between "javascript:;" and "javascript:" when used in the href attribute?

Can you explain the distinction between using "javascript:;" and just "javascript:" within an anchor tag's href attribute? ...

Why is the v-for directive malfunctioning and am I correctly displaying it in the template?

I'm new to working with Vuejs and recently created a mock dataset using JSON. The JSON file consists of an array containing 3 objects. Although console.log shows that Axios.get(URL) is fetching the data correctly, the v-for directive doesn't seem ...

Getting dynamic props from a clicked element in React involves accessing the target element's properties and

I am currently working with a React "tree" menu component that has main links with submenus generated dynamically through a JSON GET call. Upon inspecting the tree in the React Inspector, I noticed that each element has multiple props associated with it. H ...

jQuery Animated List - Nested items are unresponsive to clicks

Looking to create a dynamic nested list using jQuery for animations, but unsure of the best approach. Currently, I'm adjusting the length of the parent list item and revealing the nested items. The issue is that the parent item's length covers ...

Solving the error message: "Objects cannot be used as a React child (found: object with keys {})"

I am currently in the process of developing a full stack website that utilizes React, Express, Sequelize, and mySQL. The site is operational with features like registration and login implemented successfully. However, I encountered an issue when trying to ...

Error: Discord bot encountered a TypeError while attempting to access the property 'id' of an undefined value

After revisiting a previous Discord bot package designed to track website updates, I encountered an issue. The code was originally scraped and last edited about 8 months ago with success. However, upon running node index.js, the following error occurred. ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality: $scope.updateNumbers = function(id, checked, inputs) { if (checked === true) ...

If an element with a "hidden" display property is loaded in the browser window, will it be visible?

Is an element in a hidden display still using memory when the page is loaded? It's convenient to have many elements on a page, but if 99 elements are hidden and only 1 is displayed, does that impact the loading of the page? I'm curious if the pa ...

Delving into the World of CSS

I have been working on changing the background image using this JavaScript code, but I am not sure what to reference in the CSS file. Despite reading through everything, my screen still remains blank. $(function() { var body = $('body'); var bac ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

The data is not retrieved in the response

When creating an order, I am encountering an issue where the code is not waiting for the meal data retrieval despite using async and await. This results in my response containing empty data. Although I prefer to use async and await over promises for consi ...

Stopping the spread of popup alerts: A comprehensive guide

I'm having trouble explaining this in English;-) Whenever I select an option, an alert pops up for each choice and I don't know how to stop it. Step 1: Choose the "aaaa" option, for example 1111 alert ... Step 2: Choose the "bbbb" option, for ...

Fade in background color with jquery when scrolling

Is there a way to make the header background fade in after scrolling a certain number of pixels? The code I have sort of works, but not quite right. Any suggestions? Thank you! $(function () { $(window).scroll(function () { $(document).scrol ...

Creating a dynamic text field integrated with Google Places in Ionic 4: a step-by-step guide

I am currently implementing the google-place-api autoComplete feature in my project, but I encountered an error: TypeError: Cannot read property 'getInputElement' of undefined .html <section [formGroupName]="i" *ngFor="l ...