0

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, ''));

1
  • You need to work on returned value of .replace Commented Apr 15, 2022 at 14:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking about it, but then I noticed in the docs that's only the case if the pattern is a string, which is not the case for OP.
You're right and I'll update the answer. I probably misunderstood that part of the MDN docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.