2

I want to get an array of matches within a string. Currently, my string is a media query. I removed all new lines in the media query, so one media query might look like this:

@media (max-width: 1200px) { .container { padding-left: 0px; } .bundles {padding-right:10px} }

What I want to do is get all the classes from the media query including their style attributes. So I would like an array that look as follows:

[".container { padding-left: 0px; }", ".bundles {padding-right:10px}"]

This is my attempt:

var identifiers = mediaQuery.match(/\.(.*)}/);

I was under the assumption match would give me all matches. However I am only getting one match, so I must be doing something wrong.

matisetorm
  • 857
  • 8
  • 21
buydadip
  • 8,890
  • 22
  • 79
  • 154
  • 1
    use `(.*?)` instead of `(.*)` see http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions – chiliNUT Dec 09 '16 at 16:55
  • Possible duplicate of [How do I retrieve all matches for a regular expression in JavaScript?](https://stackoverflow.com/questions/6323417/how-do-i-retrieve-all-matches-for-a-regular-expression-in-javascript) – Anderson Green Mar 23 '19 at 18:11

2 Answers2

7

You need to use g (for global) identifier as in

var identifiers = mediaQuery.match(/\.(.*?)}/g);

See the documentation here. Also, as mentioned in the comments by @chiliNUT, you need to use .*? instead of .* in order for your regex not be greedy. See here for more.

Kalman
  • 8,001
  • 1
  • 27
  • 45
2

Try this:

/\.\w+\s*\{[^\}]+\}/

Note that it will find only simple classes, and not ids or any complex css selectors. Since you wrote classes in your question, the regex should be fine. If you need more complex matches, then improve your question ans I'll improve my answer :)

Елин Й.
  • 953
  • 10
  • 25