开发者

Regular expressions and Javascript

I have the following rege开发者_JAVA百科xp:

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,


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜