Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading