HastingsDirect
HastingsDirect

Reputation: 668

Regex match on string only, not substrings

I'm adding strings to a textarea when values in a table are clicked. It has to be possible to select and deselect values in the table, and they will add/remove themselves from the textarea. The textarea has to be a string, and the added values can't be wrapped in any other characters.

The values that are being added could potentailly have any characters in, and may have one of the other of the values as a substring, here are some examples: HOLE 1, HOLE 11, HOLE 17, HOLE (1), cutaway, cut, away, cut-away, Commentator (SMITH, John), (GOAL), GOAL

Once a value has been appended to the textarea, and it's clicked again to deselect it, I'm searching for the value and removing it like so:

var regex = new RegExp("(?![ .,]|^)?(" + mySelectedText + ")(?=[., ]|$)", 'g');
var newDescriptionText = myTextAreaText.replace(regex, '');

The regex matches correctly for strings/substrings of text e.g. cutaway and away however wont work for anything beginning with a bracket e.g. (GOAL). Adding the word boundary selector to the start of the expression \b, will make the regex match for strings that start with a bracket but wont work for strings/substrings containing the same text.

Is there a way to achieve this using regex? Or some other method?

Here's a working CodePen example of the adding/removing from table.

Upvotes: 2

Views: 2201

Answers (1)

Thomas Ayoub
Thomas Ayoub

Reputation: 29471

You can use word boundaries (\b) to avoid issue when you deselect away and have cutaway in the list. Just change the regex to:

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

Here's the code I changed to make it works:

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

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

        // Do the regex find/replace
        var annotationBoxText = annotation.value,
        cellText = regexEscape(cell.textContent), // Escape any funky characters from 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;
    };

Upvotes: 3

Related Questions