Home > Enterprise >  How do I get to know what part of a REGEX was activated?
How do I get to know what part of a REGEX was activated?

Time:08-27

According to the following code example:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");

Given a random input 'var s',

How do I know which character was removed in the final string?

If I could collect the detected character in a variable, it would be awesome.

CodePudding user response:

The replacement argument to replace can be a function. You can use that to collect the matched substrings into an array:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var removedMatches = [];
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, (match) => {
  removedMatches.push(match);
  return "";
});
console.log("These matches were removed:", removedMatches)

  • Related