Understanding how Regular Expression loops behave in TypeScript within an Angular environment

I have encountered a peculiar issue with regex. I am attempting to validate user input in a contentEditable div using regex after each keydown event. The goal is to modify the text by highlighting specific words such as "hello" or "status" with

<span style="color: purple">hello<span>
. This works well with unique words, phrases, or pasted content. However, when I define both "hello" and "hello world" as keywords and type them in the contentEditable div, the regex only matches "hello," even though "hello world" is listed first in my array of strings.

Below is the code for my function:

searchByRegEx(wordsArr: string[],  sentence: string): string {

        let matchingWords = []; // array to store matching words

        wordsArr.forEach((label) => {
            const regEx = new RegExp(label, 'gi');
            regEx.lastIndex = 0
            let match = regEx.exec(sentence);
            while (match) {
                matchingWords.push(match[0]);
                match = regEx.exec(sentence);
            }
        });

        matchingWords = matchingWords.sort(function (a, b) {
            return b.length - a.length;
        });

        matchingWords.forEach((word) => {
            sentence = sentence.replaceAll(
                word,
                `<span style='color:${InputColorsHighlightValue.PURPLE}'>${word}</span>`
            );
        });

        return sentence
    }
}

Here is how I implement it:

 if (this.labels) {
            textToShow = this.searchByRegEx(['hello', 'hello world'], textToShow)
        }

When testing in devTools, the regex correctly matches on paste, but not when typing manually. The input for the regex remains consistent:

https://i.sstatic.net/4uJ8u.png

If you encounter any issues or have advice, please feel free to provide assistance.

View live version on stack blitz

Answer №1

The regex example you provided has a few errors that need to be addressed. If your input is /hello?/gi, here are some points to consider:

  • It is redundant to include the gi flags in your regex function when they are already defined (new RegExp(label, 'gi');)
  • In JavaScript, there are two ways to use regex: new RegExp(regex) or /regex/. By using slashes like /hello/, you are using the second method. Combining both methods will not work.
  • Having a question mark after the matchable part of your regex means it does not have to match anything (which may cause issues with browser processing). To match 'hello' or nothing, remove the ?.

If you simply need to match a specific string rather than a pattern, avoid using regex. It can add unnecessary complexity and potentially impact performance negatively.

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

Guide on updating a key's value in an object

Hello, I am a newcomer to working with react redux. Currently, I have an array of objects structured like this: let result = [ {Id :'a',temp:5,data:'abc (c:1'},{Id :'a',temp:5,data:'pqr (c:1'}{Id :'a',temp ...

In this scenario, the context is being revised and adjusted upon the second attempt

const {user, setUser} = useContext(UserContext); const {auth, setAuth} = useContext(AuthContext); const handleSubmit = async (e) => { e.preventDefault(); //axios request to the backend const url = 'http://localhost:5000/home'; ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

What is the method for converting a string[] array to a record<string, boolean> format in typescript?

I have a string array that contains values I want to keep and use to create a new array called Record. For each value in the userValue array. For example: userValue: string[] = ["1111","2222","3333","4444"]; selectedOptions: Record<string, boole ...

What is the correct approach to importing the Select class in JavaScript with WebDriver?

I'm having trouble using the Select function in my code to interact with a dropdown menu. I attempted to import Select from the "selenium-webdriver" package, but it doesn't seem to be working. All of the search results I've found on this top ...

I am facing an issue where the HTML button is not properly interacting with the JavaScript function

function idk() { let cypher = {A:"G",B:"L",C:"Z",D:"E",E:"Y",F:"R",G:"D",H:"N",I:"K",J:"W",K:"J",L:"B",M:"Q",N:"F",O:"S",P:"C",Q:"V",R:"X",S:"I",T:"O",U:"M",V:"T",W:"A",X:"U",Y:"H",Z:"P"}; var answer = prompt('What cypher are you going to use 1 - 26& ...

What is the process for upgrading ag-Grid to newer versions?

In the past, I was using: "ag-grid": "^18.1.2", "ag-grid-angular": "^18.1.1" Version "^18.1.1" of "ag-grid-enterprise". However, as my license expired, I obtained new versions of the licenses. I then included: "@ag-grid-community/angular": "^22.1.1", ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...

The dependency path in the package.json file contains all the necessary files

I recently developed a JavaScript package and here is the configuration in my package.json: { "name": "packageName", "version": "1.0.0", "description": "Description of the package", " ...

Encountered an issue with md-autocomplete: Attempting to read property 'success' of an undefined element

I encountered an issue while using Material Angular framework and md-autocomplete. The error message I receive is: Cannot read property 'success' of undefined. Below is the snippet of my code: /*My app.js*/ var app = angular.module('app&apo ...

Experiencing difficulties when establishing a connection between MongoDB and Node.js

I'm encountering an issue when attempting to connect MongoDB and Node.js on my local server. Can anyone assist me with solving this problem? Below is my JavaScript code: const mongodb = require("mongodb"); // Provide the function to connect to the d ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...

What are the differences between performing a search in MongoDB (database component) and Node.js (server-side)?

1) My input consists of a string with approximately 30 comma-separated elements, such as str1, str2, str3, etc. This is represented by "INPUT_STRING". 2) Within my MongoDB collection, I have a set of "allowed_strings" which includes entries like str1, str ...

Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set. Consider the following three classes: class A { p1: C constructor() { p1 = new C("A") } } class B { p2: ...

When an Angular2 application is deployed on a server running NginX, child components fail to load

After deploying my Angular2 app on a server as a Docker image and serving it with NginX, I encountered an unexpected issue. When I ran the webpack-dev-server locally to verify if the build was successful, everything looked fine https://i.sstatic.net/wQQ7 ...

Symfony Encore does not generate the index.html file during the build process

I have been utilizing a free website hosting service for my domain. The original source code on GitHub utilizes Symfony to construct the project. "scripts": { "dev-server": "encore dev-server", "dev": " ...

Displaying array data without the need for a loop in Vue.js and Axios

I want to display data in my Vue.js 3 app without using a loop. Here is the response from my Axios API: In My Axios Api I got reponse: [{id: 2, name: "sub_title", value: "The Best Developer Team", created_at: null, updated_at: null},… ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Tips on retrieving the status code from a jQuery AJAX request

I am trying to figure out how to retrieve the ajax status code in jQuery. Here is the ajax block I am currently working with: $.ajax{ type: "GET", url: "keyword_mapping.html", data:"ajax=yes&sf="+status_flag, success: callback.success ...