2

I try to test if the following rules apply on a string:

  • Must start with uppercase letter.
  • Next characters can be either in uppercase or lowercase format.
  • Only the following characters are allowed: A-z

For instance, a string can be either String or CamelCaseString, but neither string nor Camel-Case-String nor String125. Numerics and special characters must not exist.

I found this answer in a previous post.

const isUpperCamelCase = (str) => {
  return /\b[A-Z][a-z]*([A-Z][a-z]*)*\b/.test(str)
}

I have the following test suit that tries to test the above function. Unfortunately, not all tests pass:

test('isUpperCamelCase', () => {
    expect(isUpperCamelCase('Button')).toBeTruthy()
    expect(isUpperCamelCase('GreenButton')).toBeTruthy()
    expect(isUpperCamelCase('GreenLargeButton')).toBeTruthy()
    expect(isUpperCamelCase('B')).toBeTruthy()

    expect(isUpperCamelCase('button')).toBeFalsy()
    expect(isUpperCamelCase('buttonCamel')).toBeFalsy()
    expect(isUpperCamelCase('Green-Button')).toBeFalsy() // => fail!
    expect(isUpperCamelCase('Button125')).toBeFalsy()
    expect(isUpperCamelCase('Green_Button')).toBeFalsy()
    expect(helpers.isUpperCamelCase('Green+Button')).toBeFalsy() // => fail!
    expect(helpers.isUpperCamelCase('green+Button')).toBeFalsy() // => fail!
})

If I include special characters such as (,)+- in my string the function evaluates to true when it should evaluate to false. this happens because there exists a match between the special chars, but this is not the behavior that I want. How can I solve this problem?

Note: Please add detail explanation in your answer. Thanks! :)

georgegkas
  • 417
  • 6
  • 14

1 Answers1

6

You regex needs anchors for matching beginning and ending of the string, not \b. So do:

/^[A-Z][A-Za-z]*$/
trincot
  • 317,000
  • 35
  • 244
  • 286