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
  • 26,445
  • 56
  • 171
  • 325

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
  • 179,482
  • 20
  • 216
  • 275
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
  • 6,551
  • 2
  • 19
  • 35