-1

I've got a regex problem and I've reduced it to this code:

const ENV_NAME_REGEX = '[a-zA-Z_]+[a-zA-Z0-9_]*'
const array = ["VALID", "9INVALID"]
array.forEach((item) => {
  const valid = new RegExp(ENV_NAME_REGEX).test(item)
  console.log(valid)
})

Actual output:

true, true

Expected output:

true, false

The second item in the array doesn't match the regex right (because the first char cannot be a number). So why is it outputting both as true?

halfer
  • 19,824
  • 17
  • 99
  • 186
danday74
  • 52,471
  • 49
  • 232
  • 283
  • 2
    Just an advice, whenever you are stuck with regex, use an online portal like [regex101.com](https://regex101.com/r/cN5jI4/1) that explains what your current is doing and check if it matches with requirement. – Rajesh Aug 04 '17 at 05:34

3 Answers3

1

You need anchors: ^ at the beginning and $ at the end. Otherwise, your regex matches text in the middle of the string.

const ENV_NAME_REGEX = '^[a-zA-Z_]+[a-zA-Z0-9_]*$'
// ---------------------^-----------------------^
const array = ["VALID", "9INVALID"]
array.forEach((item) => {
  const valid = new RegExp(ENV_NAME_REGEX).test(item)
  console.log(valid)
})

Side note: Barring a really good reason to do something else, use regex literal notation, rather than string notation and the constructor, so you don't have to work about double-escaping; and reuse the instance:

const ENV_NAME_REGEX = /^[a-zA-Z_]+[a-zA-Z0-9_]*$/
const array = ["VALID", "9INVALID"]
array.forEach((item) => {
  const valid = ENV_NAME_REGEX.test(item)
  console.log(valid)
})

(We know it's safe to reuse the instance because there's no g flag. When there is a g flag, it's safe if you handle it carefully.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks for the tips - regarding your side not, I've got into the habit of using string notation so I can use variables in the regex - is variable usage possible with literal notation? many thanks - will accept your answer as soon as it lets me – danday74 Aug 04 '17 at 05:38
  • 1
    @danday74: No, to build an expression with variables you do need to use the constructor. But I'd avoid the constructor when you don't need to construct the regex with variable input (in my experience, needing to build dynamic ones is quite rare). – T.J. Crowder Aug 04 '17 at 05:48
1

For RegExp.prototype.test(), a partial match is sufficient.

From the MDN documentation:

Use test() whenever you want to know whether a pattern is found in a string [...]

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

use anchors ^ and $ otherwise it will give true for partial match

marvel308
  • 10,288
  • 1
  • 21
  • 32