-1

I want to use a regex to grab, and remove, credit card numbers. I have found the following regex and tested it :

^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$

It matches correctly using a regex evaluator (eg www.regexr.com).

When I try to insert it into my code, it does not work :

var daRex = /^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/
daText = "Testing REGEX 123 4387000500875798";
daText = daText.replace(daRex, '');

Printing daText just shows the original text.

What have I done wrongly here ?

Thanks.

Simon Kiely
  • 5,084
  • 25
  • 78
  • 165
  • 4
    You are not using a regex here, but a plain text replacement. – Wiktor Stribiżew Sep 25 '18 at 10:34
  • 1
    @WiktorStribiżew question has been edited is not a duplicate of the link anymore (might still be a duplicate of another one) – ben Sep 25 '18 at 10:39
  • 1
    You have `^` and `$` so the regex will ONLY match if the ENTIRE STRING is a credit card number and won't work if it's in the middle of other text. – VLAZ Sep 25 '18 at 10:40
  • 1
    @ben Still, a duplicate of https://stackoverflow.com/questions/22758874/when-to-use-this-symbol-in-regex. And a typo, too. – Wiktor Stribiżew Sep 25 '18 at 10:40
  • 1
    I'd say it's a typographical error if not a dupe. Either way, it's not a very good question. – VLAZ Sep 25 '18 at 10:41
  • https://stackoverflow.com/questions/9315647/regex-credit-card-number-tests/#9315696 – Jai Kumaresh Sep 25 '18 at 10:49

1 Answers1

1

You have to use the proper regexp delimiter, the /.
You also need to remove the ^ and the $ otherwise it match on the full line only.

Last but not least, you want replacedText = daText.replace(daRex, ''); and not daText = replacedText.replace(daRex, '');

var daRex = /(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})/
daText = "Testing REGEX 123 4387000500875798";
replacedText = daText.replace(daRex, '');
console.log(replacedText)
ben
  • 3,507
  • 1
  • 12
  • 27
  • 1
    thank you for taking the time to explain all of my mistakes. I have now learned and improved as a result of your answer, and I appreciate that. Thanks again. – Simon Kiely Sep 25 '18 at 10:47