Skip to content
Advertisement

JS How to test if a string is only an abbreviation?

Any JS Regex expert that could help me return true if the word is only an abbreviation or else false?

Tried this regex.

/([a-z]{1}.)/gi

But it also returns true for strings like.

  • A..
  • A.B
  • B.BA..
  • Greg D. Bot

I’m trying to formulate a regex that could only return true for the following:

  • A.B.
  • A.B.C.
  • A.B.C.D.

And so on..

Advertisement

Answer

Dubious definitions of what counts as an abbreviation aside, the rules are need are:

  • Anchored to start of string
  • Anchored to end of string
  • Matches a exactly 1 letter followed by a period any one or more times

So:

/^([a-z].)+$/i

There’s no need for it to be global (because you want the entire string to match, not to find matches anywhere inside a string), and there’s no need to say {1} because that is the default.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement