Regular expression - making a character optional

Need some help with what I think should be a simple Regular Expression. I have a very simple of example for a regular expression. Please see below for my code and explain why my regular expression does return correctly for the 3rd example below. I basically want the number 8 to be optional at the beginning, but still allow abc by itself. The first 2 examples return want I want, but the 3rd does not.

function check(str) {
    return /8?abc/.test(str);
}
check("8abc"); // want to be true and returns true
check("abc"); // want to be true and returns true
check("2abc"); // want to be false but returns true

Try using /^8?abc/. The ^ marks the start of a string.

1 Like

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

1 Like