0

I need to check for classname in a string.

My string looks like this:

testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue

And I'm looking for ui-filter-hidequeue anywhere (!) in the string.

This is what I'm trying. It always returns null, althought the string I'm trying to match is there:

var classPassed = 'ui-filter-hidequeue',
    classes = 'testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue',
    c = new RegExp('(?:\s|^)' + classPassed + '(?:\s|$)');

console.log( classes.match(c) )   // returns null

Question:
Can someone tell me what I'm doing wrong in my regex?

Thanks!

frequent
  • 27,643
  • 59
  • 181
  • 333

2 Answers2

2

You need \\s. \s inside a string would escape the s, which does not need escaping, and evaluates to just a "s". I.e. when you're using literal regexps, backslash escapes the regexp characters; and strings also use backslash to escape string characters. When you build a regexp from a string, you need to think about both of these layers: \\ is string-escapey way of saying \, then \s is the regexp-escapey way of saying whitespace.

Also as other comments show, there are WAY better ways to test for class presence. :) But I just answered the direct error.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Try using this:

c = new RegExp('\\b' + classPassed + '\\b');

The \b metacharacter matches at the beginning/end of a word; it stands for boundary (as in, word boudnary).

lxop
  • 7,596
  • 3
  • 27
  • 42
  • 1
    `\b` is not appropriate, as it will also match at the boundary between the minus sign and a word. – Amadan Mar 25 '13 at 00:46
  • @Amadan, ah, good point, I sometimes forget about the minus signs being part of a 'word' in HTML classes etc – lxop Mar 25 '13 at 00:47