Rob
Rob

Reputation: 333

Detecting All Caps in a string

I am having trouble trying to write a regular expression in JavaScript that can detect a whole word of at least 2 characters that is typed in all CAPS.

This is what I have tried and it seems to work .

/\b[^\Wa-z0-9_]+\b/

however, I will detect if a user starts a string "I like you."

Since, I is capitalized it returns true, hence why I want to only detect words that are all caps of more then 2 letters.

Upvotes: 2

Views: 2616

Answers (3)

jerone
jerone

Reputation: 16881

var matches = ("hoi HOW are YOU doing?").match(/\b([A-Z]{2,})\b/g);
console.log(matches);  // ["HOW", "YOU"]

Upvotes: 3

yan
yan

Reputation: 20992

Try this as your regex:

/\b[A-Z]{2,}\b/

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545913

Your character group is needlessly complicated. If you simply want capital letters, why not use [A-Z]?

To restrict it to words of >= 2 letters, use {2,} instead of + as quantifier:

/\b[A-Z]{2,}\b/

Upvotes: 6

Related Questions