2
var text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...';

or

var text = "..<anything><anything style='color:red;'>hello</anything><anything style='color:blue; font-size:1em;'>hello</anything></anything>...";

result:

array[0] = "color:red;";
array[1] = "color:blue; font-size:1em;";
faressoft
  • 19,053
  • 44
  • 104
  • 146

3 Answers3

3

Make a temporary element and use innerHTML, then getElementsByTagName and getAttribute('style') if it's a string like that.

If it's a reference to a DOM element skip the innerHTML part.

var d = document.createElement('div'), 
    text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...', 
    styles = [];
    d.innerHTML=text;
    var els = d.getElementsByTagName('*');
    for ( var i = els.length; i--; ) {  
        if ( els[i].getAttribute('style') ) { 
           styles.push(  els[i].getAttribute('style')  )
        }
    }
    styles

The jQuery would be..

$(text).find('*').map(function() { return this.getAttribute('style') })
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
2

As has already been mentioned, it's not a great idea to use regular expressions for parsing HTML.

However, if you're determined to do it that way, this will do the job for you:

var matches = text.match(/\bstyle=(['"])(.*?)\1/gi);
var styles = [];
for(var i = 0; i < matches.length; i++) {
    styles.push(matches[i].substring(7, matches[i].length - 1));
}
Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
  • This will obviously only work if you can guarantee that the style element is valid. i.e. it always has both an opening and closing quote of the same type. – Bennor McCarthy Aug 30 '10 at 01:52
0

meder has already given the correct answer, but since a regex solution was desired I'll give one. All the usual warnings about parsing a nonregular language like HTML (or SGML, or XML) with regular expressions apply.

/<[a-z]+(?:\s+ [a-z]+\s*=\s*(?:[^\s"']*|"[^"]*"|'[^']*'))\s+style\s*=\s*"([^"]*)">/g
Charles
  • 11,269
  • 13
  • 67
  • 105
  • NULL !!!! var pattInlineStyle = /<[a-z]+(?:\s+ [a-z]+\s*=\s*(?:[^\s"']*|"[^"]*"|'[^']*'))\s+style\s*=\s*"([^"]*)">/g; var result=pattInlineStyle.exec(text); alert(result); – faressoft Aug 30 '10 at 01:48