Tips for inserting a variable into a regex pattern in JavaScript?

I need help creating a dynamic list search tool that can check for a specific name in a long list. Although I have successfully hard coded the name into the regex, I am struggling to make it dynamic. Can you assist me with this task? Below is the code snippet:

    function processString(){
  document.getElementById('textArea').value = "";
  var inputString = document.getElementById('textBox').value;
  var userIn = document.getElementById('userInput').value;
  var regex = //use variable 'userIn' for regex
  $('#textArea').html(result);

  if(result != null){
    for(var i = 0; i < result.length; i++){
      document.getElementById('textArea').value += result[i] + '\r\n';
    }
  }

}

Visit this link for more details.

Answer №1

To start, it's crucial to properly sanitize user input so that the regex engine can interpret it exactly. This insightful response outlines a handy function for achieving this:

RegExp.escape= function(s) {
      return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  };

Subsequently, we can construct the appropriate regex pattern. Presuming you intend to match names, a regex pattern resembling this may be suitable:

\b<user input here>\b

The strings can then be concatenated as follows:

var regex = new RegExp("\\b" + RegExp.escape(userIn) + "\\b", "g");

Here's the comprehensive code snippet:

function processString(){
  RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
  document.getElementById('textArea').value = "";
  var inputString = document.getElementById('textBox').value;
  var userIn = document.getElementById('userInput').value;
  var regex = new RegExp("\\b" + RegExp.escape(userIn) + "\\b", "g");
  
  var result = inputString.match(regex);
  $('#textArea').html(result);
  
  if(result != null){
    for(var i = 0; i < result.length; i++){
      document.getElementById('textArea').value += result[i] + '\r\n';
    }
  }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>List of Names</p><input type="text" id='textBox' style='width:250px;'>
<br><br>
<p>name to search for</p><input type="text" id='userInput' style='width:250px;'>
<br><br>
<input type="button" value='search' style='width:250px;' onclick='processString()'>
<br><br>
<textarea name="area" id="textArea" cols="30" rows="10"></textarea>

Answer №2

If you want to create a new regular expression, you can do so by initializing a RegExp object in the following way:

let regex = new RegExp(userInput, "ig"); // utilize 'userInput' as the regex variable

The first argument represents the value retrieved from userInput, while the second one denotes the flags. The letter i signifies case-insensitivity, and g means it will be applied globally (to search through the entire string rather than stopping after finding the initial match).

To apply this regex pattern for name comparison against a list, you can execute:

let matches = inputStr.match(regex);

This operation will bring back all instances where regex is found within inputStr.

function analyzeText() {
  document.getElementById('textArea').value = "";
  let inputString = document.getElementById('textBox').value;
  let userInput = document.getElementById('userInput').value;
  let regex = new RegExp(userInput, "ig"); // employ 'userInput' for the regex
  let matches = inputString.match(regex);
  if (matches !== null) {
    for (let i = 0; i < matches.length; i++) {
      document.getElementById('textArea').value += matches[i] + '\r\n';
    }
  }

}
<p>List of Names</p><input type="text" id='textBox' style='width:250px;'>
<br><br>
<p>Enter name to find</p><input type="text" id='userInput' style='width:250px;'>
<br><br>
<input type="button" value='Find Name' style='width:250px;' onclick='analyzeText()'>
<br><br>
<textarea name="area" id="textArea" cols="30" rows="10"></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

How to retrieve data from multiple Firebase data references using Firebase and Node.js

Currently, I am in the process of constructing a JSON API that extracts data from a reference. Subsequently, using an ID within this reference data, I aim to access additional information from another reference and compile all of this data into one object. ...

Combining Three.js with Theatre.js to animate every single keyframe

I recently incorporated the amazing Theatre.js library to add animations to a section of my website. Now I realize I need to include some animation at the beginning as well. However, when attempting to select and move all the keyframes using the studio U ...

Find all words using Regex, but make sure to exclude certain matches

I need a regular expression that can search through multiple strings and identify specific words within them: Maces Armour Evasion Shields However, I want to exclude any strings that contain these words: Swords Axes Staves For example, the following st ...

The Javascript function will only initiate upon a manual reload of the page

My function is working perfectly, but only after I reload the page once it has been loaded. This function is a timer that starts counting down from 10 to 0 as soon as the page loads (which is the intended behavior). However, when I first land on the page ...

The use of Handlebars expressions within the {{#each}} block is crucial

I am currently working on my new portfolio site and I have a question about how to place handlebars expressions inside an #each loop. The project is an express application generated by express-generator, and I am using the express-handlebars NPM package: ...

using recursion within callback functions

In my JavaScript function with a callback, I am utilizing the "listTables" method of DynamoDB. This method returns only 100 table names initially. If there are more tables, it provides another field called "LastEvaluatedTableName", which can be used in a n ...

Tips for avoiding the forward slash in a URL parameter

$.ajax({ url: "/api/v1/cases/annotations/" + case_id + "/" + encodeURIComponent(current_plink), When I use encodeURIComponent to escape slashes, it doesn't work as expected. The code converts the "slash" to "%2F", but Apache doesn't reco ...

Tips for preventing the occurrence of a final empty line in Deno's TextLineStream

I executed this snippet of code: import { TextLineStream } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7201061632425c4341445c42">[email protected]</a>/streams/mod.ts"; const cm ...

A guide on showcasing real-time data with Angular's service feature

home.component.ts <h1>{{ (reportsToday$ | async)}}</h1> <div echarts [options]="alertsDaily$ | async"> <div echarts [options]="alertsToday$ | async"> <div [onDisplay]="alertsDaily$ | async"> report.component.ts constructor( ...

Transfer information via query or retrieve from storage in Vue

When considering sending a data variable to another component, is it more efficient to send it via query using a router or save the data in-store? Which method would be more optimal? router.replace({ name: 'routerName', query: { param ...

I'm experiencing some challenges with setting up my sequelize relationships

After tirelessly searching for a solution to my problem and coming up empty-handed, I decided to reach out here. Every Google search result seems unhelpful and every link I click on is disappointingly pink. Hello everyone! I'm facing difficulties est ...

Pulling Data in Vue.js using AJAX

Currently trying out Vue.js and I must say, it's impressively simpler than Angular. My single page app is utilizing vue-router and vue-resource to connect to my API backend. The primary app.js loads vue-router and vue-resource along with separate comp ...

Utilizing TranslateHttpLoader with a service URL in ngx-translate: A step-by-step guide

My goal is to retrieve translated text from a content management system by using a service URL. While using a JSON file has been successful, I am unsure of how to utilize a service URL for this purpose. The code below is what I have tried without success: ...

How can I query mongoose for multiple properties with the select option set to false?

Within my user Schema, the default settings for the password and emailVerified properties are set to {select:false}. However, I would like to include them in the query when retrieving a user. Here is what I have attempted: const user = await User.findOne ...

When the div element reaches the top of the page, it sticks to the top and is only displayed when the user

In the center of a full-screen hero section, there is a form. When it reaches the top, its position becomes fixed and additional classes are added through a script - such as shrinking its height and adding a background. What I aim to achieve is for the fo ...

Avoid constantly updating the rendering in React by utilizing callback functions

Is there a way to prevent Component B from rendering when I am only making changes in Component A? For example, if console.log("A") is associated with Component A and console.log("B") with Component B, I expect that updating text in Component A will only ...

JavaScript object created by splitting a string

I was presented with the following string: result:tie,player:paper,computer:paper One way to handle this could be splitting it into arrays, creating an object, and parsing it. However, this approach may not be ideal. Is there a better method to convert t ...

Converting Datepicker selection to a string format in AngularJS

Can anyone help me figure out how to convert a datepicker value into a string that can be passed as a parameter to a get method without causing an error? <div ng-app="getserviceApp" ng-controller="getserviceCtrl"> <button ng-click="Func ...

Is there a way to activate an event when using # or @ in a text field on React/Next.js?

I'm in the process of starting a new project and I am thinking about how to incorporate this into react/nextjs. I want to create a user selection or hashtag selection dialog around the textarea, but I haven't been able to find any helpful article ...

Conceal Achievement Notification

The code below signifies a successful update of records. When the user is on the Edit section, they will see the msg just above the update button. I intend for this msg to go away as the user can still make edits to the records. What is the process to hi ...