I have a bunch of common regex patterns which I got from here. I try applying them to a string but they do not seem to modify anything. It just returns me the same value. Can you please enlighten me on what I am doing wrong.
const str = 'sadas87676szdhgzshdgszhjg,##%$,.%';
const commonRegexPatterns = {
DIGITS: /^[0-9]+$/,
ALPHABETIC: /^[a-zA-Z]+$/,
ALPHANUMERIC: /^[a-zA-Z0-9]+$/,
DATE: /^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$/,
EMAIL: /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/,
ZIP: /^[0-9]{5}(?:-[0-9]{4})?$/,
DIGITSWITHCOMMA: /^[\d,]/,
DIGITSWITHCOMMAPERCENTAGE: /^[\d,%]/,
}
console.log('DIGITS', str.replace(commonRegexPatterns.DIGITS, ''));
console.log('ALPHABETIC', str.replace(commonRegexPatterns.ALPHABETIC, ''));
console.log('ALPHANUMERIC', str.replace(commonRegexPatterns.ALPHANUMERIC, ''));
console.log('DIGITSWITHCOMMA', str.replace(commonRegexPatterns.DIGITSWITHCOMMA, ''));
console.log('DIGITSWITHCOMMAPERCENTAGE', str.replace(commonRegexPatterns.DIGITSWITHCOMMAPERCENTAGE, ''));
console.log('ZIP', str.replace(commonRegexPatterns.ZIP, ''));
Well, your regex patterns are wrong. Ok, not really "wrong", but they are not what you seem to want. For example, DIGITS:
^[0-9]+$
This pattern has anchors (the ^ is the start of the string, the $ is the end). It will match an entire string of numbers, but not just any number inside a string. For your purpose, you want it without the anchors, like:
[0-9]+
The same applies to most of the other patterns in your snippet. Remove the anchors if you are just trying to match part of a string.
Additionally, since you seem to be trying to remove all occurrences of patterns in the string, you probably want to use the g flag in your patterns. For example, ALPHABETIC (without the anchors):
/[a-zA-Z]+/
This will match the first group of letters in your string, but not the ones after it. If instead you use
/[a-zA-Z]+/g
You will be able to replace every match.