Click here to Skip to main content
15,903,728 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello expert,

I want to read a text file using java script. I did it in following manner..

HTML
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
<script language="JavaScript" type="text/javascript">
<!--
var srcFrame;
//External content into a layer
function loadOuter(doc) {
 srcFrame = document.getElementById("hiddenContent");
 srcFrame.src = doc;
 // workaround for missing onLoad event in IFRAME for NN6
 if (!srcFrame.onload) {
  setTimeout("transferHTML()", 1000)
 }
}

function transferHTML(){
 srcContent='';
 if (srcFrame.contentDocument){
  srcContent=srcFrame.contentDocument.getElementsByTagName("BODY")[0].innerHTML;
 }
 else if (srcFrame.contentWindow){
  srcContent=srcFrame.contentWindow.document.body.innerHTML;
 }
 document.getElementById("outerDisplay").innerHTML = srcContent
}



//-->
</script>

<INPUT TYPE="button" VALUE="input.txt" onClick="loadOuter('input.txt')" >
<div id="outerDisplay"></div>
<iframe  id="hiddenContent" width="200" height="200" style="position:absolute;visibility:hidden;" ></iframe>

</body>
</html>


Above code is able to read the text file at once and can show it in html.

Now suppose I have CSV strings in that same file, and If i need to read it into two dimensional array then what should I do here?

The link http://stackoverflow.com/questions/6861180/how-can-you-read-a-file-line-by-line-in-javascript[^] explains doing the same by using xmlHttpRequest object. But If I refere it, I could not able to read file content rather I don't know how to implement the given function in my html.

Any help please???
Posted

1 solution

CSV[^] is usually a comma (or TAB)-separated text format.
So what you can do is split[^] the text string using the new-line character first, this will give you an array of lines.
Then for each of these lines, split the line using the comma character, giving you an array of tokens for each line.
You can add[^] each of these token arrays to a new array giving you your desired 2D array

I hope this helps.
 
Share this answer
 
v2
Comments
comred 16-Oct-12 3:34am    
Thanks parths... Its help me a lot..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900