Skip to content Skip to sidebar Skip to footer

Get Id Or Class Name In Jquery Selector Use Regex By PHP

I'm trying to catch all the id and class name in the selector by PHP here's the regex which I'm using: /(?:\$|\$_|.(?:find|prependTo|closest|addClass|removeClass|toggleClass))+\(\'

Solution 1:

Okay, I just posted another question here: There must something before the string

And I think I get the answer.

BE WARE: please mind some regex will capture . and # symbols, and some won't

--

1.Get IDs and classes in selectors

ANSWER

you still couldn't get class name in addClass(), removeClass() though ..

/(?:(?:\$|\$_|\.(?:find|prependTo|closest))\(\'|(?<!^)\G)\s?([.#][-\w]+)?[^()\s.#]*(?=[^()]*\))/gm

DEMO

--

Explain

A little trick

(?:(?:\$|\$_|\.(?:find|prependTo|closest))\(\'|(?<!^)\G)

This is a little trick to confirm the ID or class in in a selector,

so you won't get .jpg in url(http://www.google.com/test.jpg),

but the bad news is, you need to add them manually when there's a new selector

Don't want to capture . and #?

You just need to remove [.#] in the regex, so you need to change

/(?:(?:\$|\$_|\.(?:find|prependTo|closest))\(\'|(?<!^)\G)\s?([.#][-\w]+)?[^()\s.#]*(?=[^()]*\))/gm
                                                              ^^^
                                                      Remove this bracket

--

2.Get classes in addClass(), removeClass()..

ANSWER

This will capture the whole content inside addClass, removeClass and toggleClass,

it's the dumbness way as far as I know.

/(?:\.(?:addClass|removeClass|toggleClass))\('(.*?)'\)/g

DEMO

--

3.Get IDs and class in CSS

ANSWER

/(?![^{]+})(?:\.|#)([_a-zA-Z]+[_a-zA-Z0-9-]*)/g

DEMO

--

The answer of this question?

Let's collect the first and second regex

/(?:(?:\$|\$_|\.(?:find|prependTo|closest))\(\'|(?<!^)\G)\s?([-\w]+)?[^()\s.#]*(?=[^()]*\))|(?:\.(?:addClass|removeClass|toggleClass))\('(.*)'\)/g

so you can now get IDs and classes in selectors,

and you still need to split classes in addClass(), removeClass() in other way.

DEMO


Post a Comment for "Get Id Or Class Name In Jquery Selector Use Regex By PHP"