cassName RegExp

3 views
Skip to first unread message

RobG

unread,
Oct 2, 2007, 8:03:09 AM10/2/07
to Fork JavaScript
I was looking over the code in the FORK Dom library when I came across
the following:

hasClass: function(el, className) {
...
var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
...
},

I seems to me that the use of a look-ahead is not required and that it
needlessly precludes older browsers that don't support it.

Is there any reason why a regular expression such as

'(^|\\s+)' + className + '(\\s+|$)'

can't be used?


--
Rob

Peter Michaux

unread,
Oct 2, 2007, 7:09:10 PM10/2/07
to forkjav...@googlegroups.com
Hi Rob,

On 10/2/07, RobG <rg...@iinet.net.au> wrote:
>
> I was looking over the code in the FORK Dom library when I came across
> the following:
>
> hasClass: function(el, className) {
> ...
> var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
> ...
> },
>
> I seems to me that the use of a look-ahead is not required and that it
> needlessly precludes older browsers that don't support it.

Agreed. This RegExp was from YUI and I didn't edit it. I looked at it
about a month ago and thought "why the ?:"

> Is there any reason why a regular expression such as
>
> '(^|\\s+)' + className + '(\\s+|$)'
>
> can't be used?

I believe that would be fine.

I made some speed tests when looking into jQuery/CSS-style element
selectors. It is faster to write

(' ' + el.className + ' ').indexOf(' foo ') != -1

than to write

el.className.match(/(^|\s+)foo(\s+|$)/);

So I was thinking the RegExp can disappear all together.

Peter

GordonHo

unread,
Oct 5, 2007, 7:47:21 AM10/5/07
to Fork JavaScript
hi,

i just stumbled over your lib and hence over this article.

the expression used in the yui does not use a lookahead, ?: is just
not grouping.

cheers, gordon

Reply all
Reply to author
Forward
0 new messages