2

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,

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this fast and relevant reply Mark!
1

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

Comments

1

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 ($)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.