balteo
balteo

Reputation: 24679

Regular expressions and Javascript

I have the following regexp:

var re = new RegExp("(^|\\s)" + classname + "(\\s|$)");

I understand \s is a white-space character; the caret means "beginning with". What I don't understand is the pipe character here...

How does the expression above translate into English?

Regards,

Upvotes: 2

Views: 78

Answers (3)

ipr101
ipr101

Reputation: 24236

The | means or so -

Match start of the line (^) or a whitespace character

Match value of classname variable

Match whitespace character or end of line ($)

Upvotes: 1

Gaijinhunter
Gaijinhunter

Reputation: 14685

The | symbol in javascript regex means "or".

You can check out a helpful list here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp#Special_characters_in_regular_expressions This was listed on the fabulous javascript regex tester site regexpal.com

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

The expression (^|\s) is an alternation. It means "either the start of the string or a whitespace character". Similarly (\s|$) means "either the end of the string or a whitespace character".

This sort of regular expression is useful for finding a word in a space separated list where there is no space at the start or end.

Upvotes: 2

Related Questions