0

im trying to find specific class patterns for a script. but my regex call is failing to find all occurrences. Instead it just returns the first one.

string = "col-xs-1 col-md-middle col-lg-middle"
s = /col(?:-(..)-|-)(?:middle|top|bottom)/g.exec(string);
console.log(s)

output -> ["col-md-middle", "md"]

does anyone know what im doing wrong here?

ceed
  • 689
  • 1
  • 6
  • 15

2 Answers2

2

Use string.match function. exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions.

> str.match(/col(?:-(..)-|-)(?:middle|top|bottom)/g)
[ 'col-md-middle', 'col-lg-middle' ]

If you want to get the match aswell as captures then use the below.

> var re = /col(?:-(..)-|-)(?:middle|top|bottom)/g;
undefined
> var m;
undefined
> var a = [];
undefined
> while ((m = re.exec(str)) != null) {
... a.push(m[0])
... a.push(m[1])
... }
4
> a
[ 'col-md-middle',
  'md',
  'col-lg-middle',
  'lg' ]

Reference

Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • can you might tell my why the original code is not working the way it should? – ceed Feb 07 '15 at 16:14
  • `re.exec` function alone return only the first match. But when it is used inside a loop, it would print all the matches, since the loop iterates until no match is found. – Avinash Raj Feb 07 '15 at 16:18
  • well logical, might be because of speed reasons, still confusing why they didnt made it gloval. anyway thx – ceed Feb 07 '15 at 16:21
0
    var t = this
        s = t.attr('class').match(/(col(-(..)-|-)(middle|top|bottom))/g).join(' ').split('-');
    $(s).each(function(k,v){
        if (k%2!==0) {
           // here i get the string after col-
        }
    });

here is my solution, a bit smaller and i like to avoid whiles, they just love to infinity loop themselves

ceed
  • 689
  • 1
  • 6
  • 15