user3050308
user3050308

Reputation: 23

Regex matches first and last character of a string, but why?

This regex will match the first and the last character of a string:

/^.|.$/g

but why? Shouldn't it be the first 'OR' the last character? Could someone explain this to me please?

Upvotes: 1

Views: 1841

Answers (2)

anubhava
anubhava

Reputation: 785481

That is matching multiple times due to use of g (global) switch.

If you want only one match then remove g flag:

/^.|.$/

Upvotes: 2

xdazz
xdazz

Reputation: 160883

/^.|.$/ matches the first or the last character, but you added the g (global) modifier, which means you will get both.

Upvotes: 1

Related Questions