jQuery: Split <td> from <tr>
I have a string containing <tr>
s and <td>
s. I want to split the data fr开发者_StackOverflow社区om the <td>
s into an array. So that this:
<tr>
<td>Test</td>
<td>Hey</td>
</tr>
<tr>
<td>Test2</td>
<td>Hey2</td>
</tr>
Becomes:
array[0] = { test, hey }
array[1] = { test2, hey2 }
var originalString = "<tr><td>Test</td><td>Hey</td></tr><tr><td>Test2</td><td>Hey2</td></tr>";
var targetArray = [];
$(originalString) /*.find("tr")*/ .each(function(index, tr) {
targetArray[index] = $("td", tr).map(function(index, td) {return $(td).text();});
});
jQuery? For what?
var array = [];
var strArray = "Test Hey Test2 Hey2".split(" ");
for (int i = 0; i < strArray.length; i += 2) {
array[i] = [strArray[i], strArray[i + 1]];
}
Edit (according to your edit)
var array = new Array();
$("tr").each(function() {
array.push([ $(this).find("td:eq(1)").text(), $(this).find("td:eq(2)").text() ]);
});
EDIT: Here's a much shorter JQuery version of the below (I tested on jQuery 1.4.2):
function split(s) {
return $.map(s.split('<tr>').slice(1), function(i) {
return [$.map(i.split('<td>').slice(1), function(i) {
return i.split('</td>')[0]
})]
})
}
var L = split('<tr><td>Test</td><td>Hey</td><tr><td>Test2</td><td>Hey2</td></tr>');
Here's the previous raw JavaScript version which is still probably faster than the above:
function split(s) {
var L = s.split('<tr>');
var rtn = [];
for (var x=1; x<L.length; x++) {
var iL = L[x].split('<td>')
iRtn = []
for (var y=1; y<iL.length; y++) {
iRtn.push(iL[y].split('</td>')[0]);
}
rtn.push(iRtn)
}
return rtn;
}
var L = split('<tr><td>Test</td><td>Hey</td><tr><td>Test2</td><td>Hey2</td></tr>');
I've tested it to work on basic strings with tables in them, but it doesn't unescape e.g.
etc and it obviously won't handle nested tables. Should be faster using only string split methods, but I'm sure it can be done shorter with JQuery $(x).map
. It also requires the table <tr>
and <td>
's to be lowercased as it's written.
精彩评论