开发者

Javascript: Regex to get values from string

I suck at regexes so need some help with this, if I pass the below string into someFunction(str)

<table width="100%" border="0" cellspacing="2" cellpadding="2" bgcolor="red"> 

how can I get back an array like so:

arr[table] = "";
arr[width] = "100%";
arr[border] = "border";
arr[cellspacing] = "cellspacing";
arr[bgcolor] = "cellpadding";

o开发者_Go百科r in other words, the first part of the array the tag name and the other parts its properties.

Thanks!


This is the way I would handle it:

var str = '<table width="100%" border="0" cellspacing="2" cellpadding="2" bgcolor="red">'
var arySplits = str.split(' ');
var aryFinalVals = new Array();

for (var i = 0; i < arySplits.length; i++) {
    var arySubSplits = arySplits[i].split('=');
    aryFinalVals[arySubSplits[0].replace(/</, '')] = (arySubSplits[1]) ? arySubSplits[1].replace(/"/g, '').replace(/>/, '') : '';
}

Summary:

  1. Split string using the spaces.
  2. Loop through the array of property pairs and split by the =.
  3. Remove the double quotes and closing tag.


You can try this:

/([a-z]+)="([a-z0-9%]+)"/g

This is quick and dirty, though, not very resilient to variations... more "blindly":

/([^=]+)=("[^"]+")/g

the latter one will match everything that is not = just preceding a =, then ignore the = and match what is between ".


If you just want to convert a string to a DOM object, you should be able to use innerHTML to invoke the browser's HTML parser:

var strToObj = function(str) {
    var el = document.createElement('div');
    el.innerHTML = str;
    return el.childNodes[0];
}
document.body.appendChild(strToObj('<table width="100%" border="0" cellspacing="2" cellpadding="2" bgcolor="red">'))


A quick and dirty proof of concept:

var input = '<table width="100%" border="0" cellspacing="2" cellpadding="2" bgcolor="red">';
var properties = {};
var tempNode = document.createElement("div");
tempNode.innerHTML = input;

for(var p in tempNode.firstChild.attributes){
    if( tempNode.firstChild.attributes.hasOwnProperty(p) ){
        properties[tempNode.firstChild.attributes[p].name] = tempNode.firstChild.attributes[p].value;
    }
}

It's not fully tested and it makes lots of assumptions, but I hope it can give you an idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜