0

I'm writing a script to check if there's occurence of amex credit card number inside a string.

My code looks like this:

let amexRegex= /^3[47][0-9]{13}$/;

if(text.search(amexRegex) != -1){
    console.log('Found!');
} else {
    console.log('Not found!');
}

When I set textto '378734493671000' (a valid amex credit card number), script prints out Found!, but if I keep that same text and add some text arround it, like this: '378734493671000 ABCDEFG', it prints out Not found!.

What should I change in order to find occurence of substring matching the regex? I don't need a index of substring matching the regex, just true\false.

4 Answers 4

2

The ^ and $ restrict matching to beginning and end of string, respectively. It's probably enough to remove those.

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

Comments

2

You just need to remove ^ and $ which respectively match stat and end of line:

let amexRegex= /3[47][0-9]{13}/;

Comments

1

Pay attention that only removing ^ and $ can lead to incorrect matches, such as longer numeric strings. You better replace them by word boundaries:

\b3[47][0-9]{13}\b

Demo

Comments

1
let amexRegex = /3[47][0-9]{13}/

if(amenxRegex.test(text) {
  console.log('Found!')
} else {
  console.log('Not found!')
}

Comments

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.