how to get style="i want the css code" using regexp (javascript)
var text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...';
or
var text = "..<anything>开发者_Go百科<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;";
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') })
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));
}
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
精彩评论