How do I convert escape characters in Javascript to a .txt file? - javascript

I have an HTML file that is using Javascript to do file I/O operations on a .txt file, via an ActiveXObject (only works in Internet Explorer, on Windows OS).
There is a text input box on the HTML page, and a button. The button calls a function onclick to write the text entered to the end of the .txt file. There is also a textarea on the HTML page, in which the modified contents of the .txt file are copied and pasted into. All of this is working so far...
So, I want to insert tabs and new-lines into the .txt file, from my HTML page with Javascript. I am using this line to copy the .txt file contents into the textarea, initialized in a variable:
var newText = oldText + "\n" + document.getElementById("userInput").value;
Of course, the escape character \n works on the HTML page, and not in the .txt file...
So how do I encode new lines, and tabs as well, into a parsable format for the .txt file? I have tried using the escape() method on ANSI values found here, and on ASCII values found here, but with no luck.
Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<body>
<p>
Enter some text here:
<input type = "text" id = "userInput" />
</p>
<input type = "button" value = "submit" onclick = "main();" />
<br />
<hr />
<br /><br /><br />
<textarea id = "textHere" rows = 25 cols = 150></textarea>
<script type = "text/javascript">
// executes all code from this function to prevent global variables
function main()
{
var filePath = getThisFilePath();
var fileText = readFile(filePath);
writeFile(filePath, fileText);
} // end of function main
function getThisFilePath()
{
var path = document.location.pathname;
// getting rid of the first forward-slash, and ending at the last forward-slash to get rid of file-name
var correctPath = path.substr(1, path.lastIndexOf("/") );
var fixedPath = correctPath.replace(/%20/gi, " "); // replacing all space entities
return fixedPath;
} // end of function getThisFilePath
function readFile(folder)
{
var fso = "";
var ots = "";
var oldText = "";
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "read" mode (1)
ots = fso.OpenTextFile(folder + "writeToText.txt", 1, true);
oldText = ots.ReadAll();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
return oldText;
} // end of function readFile
function writeFile(folder, oldText)
{
var fso = "";
var ots = "";
var newText = oldText + "\n" + document.getElementById("userInput").value;
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "write" mode (2)
ots = fso.OpenTextFile(folder + "writeToText.txt", 2, true);
ots.Write(newText);
ots.Close();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
setText(newText); // with the function below
} // end of function writeFile
// called from the function writeFile
function setText(textFile)
{
document.getElementById("textHere").value = textFile;
} // end of function setText
</script> <!-- end of javascript -->
</body>
</html>

Windows expects "\r\n" as linebreaks. I'm quite sure you would find them in your textarea's value as well (after hitting enter). They will get automatically inserted when you set a value with "\n", and most libraries (like jQuery) do replace them with "normal" linebreaks when reading the value.
However, I would expect a file read/write with only "\n" to work, and when you load the file's text into your textarea they should show up. MS Notepad might have problems showing them.

Related

I want to extract a string from a text file and output it as a text file again

I want to extract a string from a text file, convert it to a word scrambler (I figured out that part) and output it in another text file.
I found some code to input a text file and extract the text:
<html>
<h4>Select un file con .txt extension</h4>
<input type="file" id="myFile" accept=".txt" />
<br /><br />
<div id="output"></div>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function (e) {
output.textContent = e.target.result;
});
reader.readAsText(myFile);
}
});
</script>
</html>
Input text and extract a text file
<html>
<div>
<input type="text" id="txt" placeholder="Write Here" />
</div>
<div>
<input type="button"id="bt"value="Save in a File"onclick="saveFile()"/>
</div>
<script>
let saveFile = () => {
const testo = document.getElementById("txt");
let data = testo.value;
const textToBLOB = new Blob([data], { type: "text/plain" });
const sFileName = "Testo.txt";
let newLink = document.createElement("a");
newLink.download = sFileName;
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
newLink.click();
};
</script>
</html>
But I don't know how to output a string in the first code or how to connect it to the second code. Could someone please show me how to do it or explain how these codes work so that I could try to do it myself in JavaScript?
I will comment each line of JavaScript, that should help you understand.
<script>
/*This creates a global variable with the HTML element input in it. */
var input = document.getElementById("myFile");
/*This creates a global variable with the HTML element div with id output in it. */
var output = document.getElementById("output");
/* this 2 lines are used to set the source and the destination.
The first will get where you put your file, in this case it's the input element.
The second will get the div which content will be replaced by the content of your txt file. */
/* Here we tell to our input element to do something special when his value changes.
A change will occur for example when a user will chose a file.*/
input.addEventListener("change", function () {
/* First thing we do is checking if this.files exists and this.files[0] aswell.
they might not exist if the change is going from a file (hello.txt) to no file at all */
if (this.files && this.files[0]) {
/* Since we can chose more than one file by shift clicking multiple files, here we ensure that we only take the first one set. */
var myFile = this.files[0];
/* FileReader is the Object in the JavaScript standard that has the capabilities to read and get informations about files (content, size, creation date, etc) */
var reader = new FileReader();
/* Here we give the instruction for the FileReader we created, we tell it that when it loads, it should do some stuff. The load event is fired when the FileReader reads a file. In our case this hasn't happened yet, but as soon as it will this function will fire. */
reader.addEventListener("load", function (e) {
/* What we do here is take the result of the fileReader and put it inside our output div to display it to the users. This is where you could do your scrambling and maybe save the result in a variable ? */
output.textContent = e.target.result;
});
/* This is where we tell the FileReader to open and get the content of the file. This will fire the load event and get the function above to execute its code. */
reader.readAsText(myFile);
}
});
</script>
With this I hope you'll be able to understand the first part of this code. Try putting the second part of your code instead of output.textContent and replacing data with e.target.result, that should do what you wish, but I'll let you figure it out by yourself first, comment on this answer if you need further help !
Here's a codepen with working and commented code:
https://codepen.io/MattDirty/pen/eYZVWyK

JS Keep Character's Regular Value

When I run my snippet (shown below), it replace the dashes (-), the single quote, and the double quote with �.
var button = document.querySelector('#fileInput + button');
var input = document.getElementById('fileInput');
var text = null;
input.addEventListener("change", addDoc);
button.addEventListener("click", handleText);
function addDoc(event) {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
text = reader.result;
button.removeAttribute("disabled");
};
reader.onerror = function(err) {
console.log(err, err.loaded, err.loaded === 0, file);
button.removeAttribute("diabled");
};
a = reader.readAsText(event.target.files[0]);
console.log(a);
}
function handleText() {
addtoPreviousOutput();
changeOutputParagraph(text);
button.setAttribute("disabled", "disabled");
}
function changeOutputParagraph(newText) {
var element = document.getElementById("output");
element.innerHTML = newText;
}
function addtoPreviousOutput() {
var previousOutput = document.getElementById("output").innerHTML;
var previousOutput_sOutput = document.getElementById("previousOutput").innerHTML + "<br />";
console.log(previousOutput);
console.log(previousOutput_sOutput);
document.getElementById("previousOutput").innerHTML = previousOutput_sOutput + previousOutput;
}
<p id="previousOutput"></p>
<p id="output"></p>
<input type="text" id="textInput" onkeypress="getText(event)" />
<input type="file" id="fileInput" accept="text/*" />
<button type="button" id="addDoc">Add Document</button>
Why is that and how do I fix it?
Edit
I get this when I run my file which is 176 lines and 22 KB. Note: This isn't all of the text.
readAsText reads the text as utf-8 by default. The reason you see � instead of your expected characters is because your text file is not utf-8 encoded.
You can pass the encoding of your file to readAsText to properly read the text.
e.g. for latin 1
a = reader.readAsText(event.target.files[0], 'ISO-8859-1');
A FileReader can only read one file at the time, however you're trying to read the file twice:
reader.readAsText(event.target.files[0]);
console.log(reader.readAsText(event.target.files[0]));
There's no actual reason for you to do that. Just store the first read result - and print the data that you've already read.

Add Dynamic Variable in URL Content in JQuery

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:
string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
{
strFileName = Path.GetFileName(strFile);
}
<img id="myImg" src="#Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="#strFileName"/>
In script section, I am trying to get this hidden field value:
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName');
//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '#Url.Content("~/Content/AnnouncementImages/" + filename);
}
I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.
#{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="#strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName').value;
//This is not working so far since it says cannot resolve symbol filename on below code:
var src = '#Url.Content("~/Content/AnnouncementImages/")' + filename;
alert(src);
}
</script>

Adding junk character in currency symbol while exporting data to CSV

I am getting strange Issue that whenever I am exporting the data in csv which have a currency symbol, It has added junk extra character in the data beside the currency symbol.
For example if My data = France - Admin Fee 1 x £100
I am getting the result like = France - Admin Fee 1 x £100 when i open this in Excel. My code is :
<html>
<head>
<script type="text/javascript">
function CreateCSV()
{
var buffer = "France - Admin Fee 1 x £100";
buffer = "\"" + buffer + "\"";
// buffer = "" + euro; //"\u2034";
var uri = "data:text/csv;charset=UTF," + encodeURIComponent(buffer);
var fileName = "InvoiceData.csv";
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
link.setAttribute("href", uri);
link.setAttribute("download", fileName);
}
else if (navigator.msSaveBlob) { // IE 10+
link.addEventListener("click", function (event) {
var blob = new Blob([buffer], {
"type": "data:text/csv;charset=UTF;"
});
navigator.msSaveBlob(blob, fileName);
}, false);
}
else {
// it needs to implement server side export
}
link.innerHTML = "Export to CSV";
link.click();
}
</script>
</head>
<body>
<input type="button" value="Download CSV" onclick="CreateCSV()" />
</body>
</html>
When i open the same in notepad. I cannot see the junk character. I am very thankful if you can get me a work around.
The character set should probably be UTF-8. Also check the unicode for the £, I do believe it is u2034. You can find a chart here, and it lists it as U+00A3. If you have something more advanced than just Notepad, like Notepad++ for example, check the encoding type when you open the time. Excel can be finicky.

How do I import, edit, and replace text in a txt file?

Using a client side script in a webpage (no server code), like javascript, how do I import, edit, and replace text in a txt file? I am simply trying to use two variables (Name and IP Address) and replace them in a text file. The existing text file is very long and I would like to automate this process. It would be nice for the script to also automatically create a new text file each time it is submitted. THANKS!
Here's my code:
<html>
<head>
<title>TExt File Changer v1</title>
<script type="text/javascript">
function findaNamendReplaceAll() {
var findaName = "Site_Name";
var findaCIP = "192.168.0.5";
var replaceaName = document.myInput.replaceWithName.value;
var replaceaCIP = document.myInput.replaceWithCIP.value;
var fulltexta = document.myInput.fulltext.value;
/*
var nr = new RegExp(findaName,"ig");
var tmp = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5 /gi,replaceaCIP);
document.myInput.fulltext.value = tmp;
*/
document.myInput.fulltext.value = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5/gi,replaceaCIP);
}
var str += ‘SECTION ethernet’/n;
str += ‘ETHERNET=UP’/n;
str += ‘BOOTP=server’/n;
str += ‘HOSTNAME=Site_Name’/n;
str += ‘IPADDR=192.168.0.4’/n;
str += ‘NETMASK=255.255.255.0’/n;
str += ‘DNS=‘/n;
str += ‘DHCP_RANGE_L=192.168.0.20’/n;
str += ‘DHCP_RANGE_U=192.168.0.100’/n;
str += ‘SEARCH=‘/n;
str += ‘ZEROCONF=YES’/n;
str += ‘ETH0_ADD_DEFAULT=on’/n;
str += ‘ENDSECTION ethernet’/n;
str += ‘‘;
</script>
</head>
<body>
<form name="myInput" onsubmit="return false">
<h1>Configuration Tool</h1>
New Site Name: <input type="text" id="replaceWithName" name="replaceWithName" value="">
<br><br>
New Camera IP: <input type="text" id="replaceWithCIP" name="replaceWithCIP" value="">
<br><br>
<button onclick="findaNamendReplaceAll()">Go</button>
<br><br>
<textarea id="fulltext" name="fulltext" rows="20" cols="100">
SECTION ethernet
ETHERNET=UP
BOOTP=no
HOSTNAME=Site_Name
IPADDR=192.168.0.4
NETMASK=255.255.255.0
DNS=
DHCP_RANGE_L=
DHCP_RANGE_U=
SEARCH=
ZEROCONF=YES
ETH0_ADD_DEFAULT=on
ENDSECTION ethernet
</textarea>
<br>
<button onclick="document.getElementById('fulltext').value = ''">Clear</button>
<button onclick="document.getElementById('fulltext').value = str">Restore</button>
</form>
</body>
</html></pre>
You can do it easily, provided you adhere to two limitations.
1) Internet Explorer on windows
2) Use of ActiveXObjects
I did a project that required assembling various data as found in excel spreadsheets. My input file was a hand-edited json file - specifying things like filenames and paths. Once the json was loaded, I used an ActiveXObject to open and control Excel in just the same manner as one would from within a VBA program.
As a result, I don't have any code to load arbitrary data from an arbitrary filename.
However, this snippet should give you enough to get started.
Note: The code assumes that IE still gives you a fully qualified path for any file selected with an <input type='file'/> Chrome, FF and Opera only give you the filename - they do not tell you which folder it resides in.
function byId(e){return document.getElementById(e);}
function writeDataToFile()
{
var mFSO = new ActiveXObject("Scripting.FileSystemObject");
var mFile = mFSO.createtextfile(outputFilename);
mFile.write( byId('outputTextArea').value );
mFile.close();
alert("text saved to '" + outputFilename + "'");
}

Categories