Regular expression confusion

Hi Guys.

I cannot figure out why this:

/^[^\d\-]$/.test("Enter")

returns false. Can anyone help?

Because it isn’t a digit followed by a dash.
https://regex101.com/r/AJc3UF/1

Test for “not single digit or single minus sign”.

/regex/.test(“1”) should return false, but /regex/.test(“12”) or /regex/.test("+") should return true. I can see that

/[^\d\-]/

does what I want, but I don’t understand why adding the beginning and end markers breaks the regex.

EDIT: no it doesn’t. /[^\d-]/.test(“12”) returns false :frowning:

The issue is that you’re not specifying a quantity. You’re asking the regex engine for “any single character that is not a digit or a dash that is both the first and last character in the string”. Depending on what are looking to test, you will probably want to change the “single character” part and look for “one or more characters”. Add a plus sign (+) to do this.

/^[^\d\-]+$/.test("Enter")

The problem with this is that you can’t match multiple numbers. You could think about matching only for what you want to find, multiple numbers and letters.

/[\d\w]{2,}/.test("Enter") // true
/[\d\w]{2,}/.test("1234") // true
/[\d\w]{2,}/.test("1") // false

The question is, are you looking to exclude just single dashes, or any expression with a dash in it?

/[\d\w]{2,}/.test("-") // false... right?
/[\d\w]{2,}/.test("1234-5678") // true or false?

Before posting here I did try to specify the amount as {1}, because I also want target single letters:

_regex_.test("a") // shoud return true, as it is "not a single digit or single minus sign"

I think that

!/^(\d|\-)$/.test(key)

works well, but I ended up dropping the test altogether and working with a new scope added to my calcKeyTest() function.

EDIT: Result: https://codepen.io/pwkrz/pen/zRRObG?editors=1011