Matching regex only on complete strings, not on parts of strings

My goal is to dynamically add and remove strings to a textarea when values in a table are clicked. The functionality should allow users to select and deselect values in the table, with the selected values adding or removing themselves from the textarea. It is important that the values added to the textarea remain as plain strings without any additional characters.

The values being added may contain any characters and could potentially have one value as a substring of another. For example, values like HOLE 1, HOLE 11, cutaway, cut, Commentator (SMITH, John), and (GOAL) are all possibilities.

When a value is clicked to deselect and remove it from the textarea, I am currently using a regex to find and replace the value. However, the current regex pattern works for most cases except for strings starting with a bracket, such as (GOAL). Adding a word boundary selector \b to the regex improves the matching for strings starting with a bracket, but it may affect the matching of substrings within the text.

I am wondering if there is a way to improve the regex or perhaps explore other methods to achieve the desired functionality. Here is a CodePen example demonstrating the adding and removing values from the table.

Answer №1

To prevent issues when deselecting away but still having cutaway in the list, you can utilize word boundaries (\b). Simply modify the regex as follows:

regex = new RegExp("(?![ .,]|^)?(\\b" + cellText + "\\b)(?=[., ]|$)", 'g');
                                 ^^^                ^^^

Below is the code that was modified to ensure it functions correctly:

removeFromDescription = function(cell) {
        cell.classList.remove(activeClass);

        // Remove from the active cells array
        var itemIndex = tempAnnotation.activeCells.indexOf(cell.textContent);
        tempAnnotation.activeCells.splice(itemIndex, 1);

        // Perform the regex find/replace
        var annotationBoxText = annotation.value,
        cellText = regexEscape(cell.textContent), // Escape any special characters in the string

        regex = new RegExp("(^| )" + cellText + "( |$)", 'g');

        var newDescription = annotationBoxText.replace(regex, ' ');

        setAnnotationBoxValue(newDescription);

        console.info('cellText:         ', cellText);
        console.info('annotationBoxText:', annotationBoxText);
        console.info('newDescription:   ', newDescription);
    };

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

    setAnnotationBoxValue = function(newValue) {
        annotation.value = newValue;
    };

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

"error: unable to retrieve message channel name, result is undefined

Hey there, I'm currently experiencing an issue while trying to retrieve the name of a channel that I created. Strangely enough, it's returning undefined, even though I am certain that the channel exists. Let me share with you the code snippet wh ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Calculate a value within a MongoDB field

Hello everyone, I have a document in my collection that looks like this: { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 } I have around 200 similar documents in my collection. The Player_Rank is determined by the total Weighted ...

What is the best way to resolve an npm build error on Windows 10?

I have exhausted all options but still cannot successfully install any npm modules. Any suggestions on how to resolve this issue? Microsoft Windows [Version 10.0.17134.590] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\Dell&bsol ...

Is there a way to arrange list items to resemble a stack?

Typically, when floating HTML elements they flow from left to right and wrap to the next line if the container width is exceeded. I'm wondering if there's a way to make them float at the bottom instead. This means the elements would stack upward ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

(Critical) Comparing AJAX GET Requests and HTTP GET Requests: identifying the true client

When a typical GET request is made through the browser, it can be said that the browser acts as the client. However, who exactly serves as the client in the case of a GET request via AJAX? Although it still occurs within the browser, I am intrigued to delv ...

Adding dynamic text to a <span> tag within a <p> element is causing a disruption in my layout

I'm encountering an issue with a Dialog box that displays a message to the user regarding file deletion. Here's how it looks: +-----------------------------------------------------------------------+ | Delete File? ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Steps to generate an error in the 'response' function of a $httpProvider interceptor

I am currently working on creating a custom HTTP interceptor in Angular and I am looking to generate an error from the response of the $httpProvider interceptor. According to the provided documentation: response: Interceptors are triggered by the http re ...

Switch up the background picture by chance when hovering over it with the mouse

Would you like to change the background image when hovering over an album, similar to Facebook's functionality? When hovering over an album, display a preview of 3-4 images randomly selected. How can this be achieved using jQuery? I have tried impleme ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

SimpleModal Jquery experiencing intermittent flashing in Firefox

While utilizing the SimpleModal plugin for jQuery, I've encountered an unusual issue specific to Firefox (other browsers such as Chrome, Safari, Opera, and IE are working perfectly). The problem arises when I click on the button that triggers the mod ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

The parent's setState does not trigger the child's componentWillReceiveProps

Within my application, there is a parent component and a child component with props connected to the parent's state. When I call setState in the parent component, the componentWillReceiveProps function of the child component does not always get trigg ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...