shirishc
shirishc

Reputation: 35

RegExp word boundary with special characters (.) javascript

I want to find "U.S.A." (without the quotes) if it is in a string as a whole word.

So good strings should be

U.S.A.
u.s.a.
U.S.A. is a great country
Is this U.S.A. ?

Bad string is

U.S.A.mnop
U.S.A

I tried using

/\bU\.S\.A\.\b/i

But strangely the one that works is - (But it fails for other countries and so not useful)

/\bU\.S\.A\.\B/i

This seems opposite of my understanding from documentation and have searched this and there are lots of similar problems but none of them helped me understand the issue. I think that the last "." is being consumed by \b and hence not working but am still confused.

Can someone please help with explanation and the right search string ? It should also do proper word search of other strings without special characters.

Upvotes: 3

Views: 2785

Answers (1)

KevBot
KevBot

Reputation: 18898

You can check for the word boundary first (as you were doing), but the tricky part is at the end where you can't use the word boundary because of the .. However, you can check for a whitespace character at the end instead:

/\b(u\.s\.a\.)(?:\s|$)/gi

Check out the Regex101

Upvotes: 5

Related Questions