views:

52

answers:

3
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;";
+3  A: 

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
I'd agree to use the DOM if you're trying to parse valid xml/html. That's what Javascript is for! No sense in using regex where regex doesn't belong.
efritz
I don't want this way.
faressoft
Regex *will* break if there are nested elements and invalid HTML. That's why it's not preferred.
meder
Can i do that with jQuery ?
faressoft
It's even easier with jQuery, yes. Updated answer.
meder
This really is the way you should do it.
Bennor McCarthy
A: 

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
NULL !!!!var pattInlineStyle = /<[a-z]+(?:\s+ [a-z]+\s*=\s*(?:[^\s"']*|"[^"]*"|'[^']*'))\s+style\s*=\s*"([^"]*)">/g;var result=pattInlineStyle.exec(text);alert(result);
faressoft
+1  A: 

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
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