Marcelo Assis
Marcelo Assis

Reputation: 5214

How can I use a Regex to get the value from an attribute from a specific tag?

Example: If I have a string segment and need to get all values from width, only from img tags, I don't know how to do it using only one Regex.

By my current knowledge in regex, I would use 3 regexes to do this: First I get all desired HTML tags first (/\<img(.*?)\/?\>/g), then the attribute (/width=\".*?\"/g), and finally, get the content between quotes (/\".[0-9]*?\"/g).

EDITED: Ps.: I'm just asking this for learning purposes in Regex, I'm not planning to parse HTML documents. Currently I get this information using Jquery ($("img").attr('width'))

Upvotes: 0

Views: 82

Answers (1)

vks
vks

Reputation: 67988

\<img.*?\bwidth=\"(.*?)\".*?\/?\>

This will club your regexs together and get you the desired result.

See demo.

http://regex101.com/r/kM7rT8/8

Upvotes: 2

Related Questions