Reputation: 5406
I'm trying to use javascript with jQuery to convert a tab delimited string to html table.
In the input string rows are separated by <br/>
and columns by tabs
.
Here's what I have so far:
$(function(){
$('div.jstable').each(function(){
var text = $(this).html();
var rows = text.split(/<br>/i);
var htmlString = "<table class='display dataTable'>"
var startTbody = true;
for(i = 0; i< rows.length; i++){
// build header section
if (i == 0){
htmlString += '<thead>';
}else {
if (startTbody){
htmlString += '<tbody>';
startTbody = false;
}
}
htmlString += '<tr>';
var row = rows[i];
var columns = row.split('\t');
// build columns
for (j = 0; j < columns.length; j++ ){
if (i == 0){
htmlString += '<th>' + columns[j] + '</th>';
}else {
htmlString += '<td>' + columns[j] + '</td>';
}
}
htmlString += '</tr>';
if (i == 0){
htmlString += '</thead>'
} else {
if (i == rows.length - 1){
htmlString += '</tbody>'
}
}
}
htmlString += '</table>';
$(this).html(htmlString);
})
});
And here is the input text:
<div class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</div>
Unfortunately in IE8/7 the text returned by jquery .html() function has all tabs replaced by spaces.
IE9 is fine, also current versions of Firefox & Chrome work fine.
Any ideas?
Upvotes: 2
Views: 371
Reputation: 5406
FWIW I found out that if I surround the input text with <pre>
tags the .html() function will return the text with tabs in IE7/8, as expected.
So, the initial example source html will look like this:
<pre class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</pre>
Upvotes: 1
Reputation: 262979
You can pass a regular expression to split(). /\s+/
will consider consecutive whitespace of any kind as a single delimiter:
>>> "one two".split(/\s+/)
["one", "two"]
>>> "one\ttwo".split(/\s+/)
["one", "two"]
>>> "one\ntwo".split(/\s+/)
["one", "two"]
Upvotes: 2