Javascript: Insert text at specified line - javascript

I am kind of new to javascript, but I was looking to see if it was possible to add a line of text to a file at a specified position? i.e. every file needs to have the same text inserted at line no. 3
Someone suggested "split by line feed, add data, then rejoin", but i have no clue how to do that. Just looking for somewhere to get started or pointed in the right diretion.

Split by line feed:
data = data.split(/\r?\n/);
Add data:
data = data.splice(2, 0, new_data);
Rejoin:
data = data.join("\r\n");

Related

Node.js: How to read the last non-empty line only of a txt file?

Let's say I have a text file called example.exe that is like this:
Line 1 Stuff
Line 2 Stuff
(more lines here)
Line N (Last Line) Stuff
(empty line \n)
I want to be able to read the last line of the file only, so in this case "Line N (Last Line) Stuff" and store it inside a string. Also, I do know you can read line-by-line, but I want to reduce runtime and not have out of memory errors occur as the text file gets bigger. Anybody want to help me with this? I would prefer no this done using require('fs').
Assuming you store the content in a variable content you can split the content by lines...
var lines = content.split("\n")
...and check if the last line is empty...
var lastLine = lines[lines.length-1].length ? lines[lines.length-1] : lines[lines.length-2]

getElementByClass Split and then Display string + html

this is my first ever question and im sure its clear that I am new to this but hungry to learn! Any help is very appreciated.
I have a page where I need to grab the text of a class and then split it, displaying the first part [0] as a string and the end of the string 1 as an .
the string / iframe is separated by ##.
an example is
description description description ## <iframe>
currently the page displays it all as one long string.
as far as I have got is the follow:
var musicPlayer = document.getElementsByClassName(".program-description-text");
var fields = musicPlayer.split('##');
var myVideoDescription = fields[0];
var embedLink = fields[1];
Im sure this is wrong but assuming its not i still dont know how to display the results and how to call this to go grab and split the class string.
Thank you to anyone who takes the time to read this.
Edit:
I guess im so new that I can not find the right description for what I would like to achieve so I have taken some screen shots and edited one to show what I would like the result to be.
musicPlayer will likely be an array. You should try to console.log the musicPlayer and see what it contains.

Javascript way to create multiple HTML containers?

I've been following this tutorial: http://mariechatfield.com/tutorials/firebase/step5.html
But I wanted to spice it up and instead of printing the last database object, I want to print all of them.
I've tried printing off the database, which works fine. I just need to edit the Html. I tried using a line break, but nothing either. It keeps appending to the starting string instead of making a new line/container.
recommendations.limitToLast(10).on('child_added', function(childSnapshot) {
// Get the recommendation data from the most recent snapshot of data
// added to the recommendations list in Firebase
recommendation = childSnapshot.val();
console.log(recommendation);
// Update the HTML to display the recommendation text
$("#title").append(recommendation.title)
$("#presenter").append(recommendation.presenter)
$("#link").append(recommendation.link)
var x = '\n';
x;
// Make the link actually work and direct to the URL provided
$("#link").attr("href", recommendation.link)
});
I hope to be able to have an individual container for each database element.
Per request, posting comment as answer:
Great job! The only change you have to make is to change \n to <br>. HTML removes whitespace (like your newline). So to replicate that line break you have to use the HTML BR element. Then you'll need to append that to your existing HTML of-course.

ejs won't print a new line in a variable

I have a web app in Node.js/MySQL where users can upload their stories. They write in an HTML textarea tag. Now I'm trying to get the uploaded from the database using ejs into a script tag so I can do further 'processes'
<script>
var text = "<%=story.Content%>",
result = anchorme.js(text);
document.getElementById('story-content').innerHTML = twemoji.parse(result);
</script>
Problem is if the user hit enter to start on a new line while writing. It'll give me an error here in the text variable and nothing will be printed so how do I fix this?
If you view source on the page so that you can see how the browser receives it, you'll see something like this - note the line feeds:
var text = "I am a story over multiple lines
and that's what javascript gets confused about
because it can't figure out where the closing quotes are.
Let's not even go into what could happen when someone uses quotes!"
So you really just need a way to pass the story content to javascript without it breaking the page. Instead of just pushing out the string like this...
var text = "<%=story.Content%>"
...you can pass stuff to javascript in JSON format as that allows and escapes newlines into \r\n and quotes into \" and so-on. Note the use of <%- rather than <%= here because you don't want it to pass escaped HTML:
var text = <%-JSON.stringify({ content: story.Content })%>.content;
That passes an object with a nicely escaped string in it to your inline script for it to carry on processing.

read/write csv file using javascript in .htm

Intro:
I'm trying to make a html application (.htm) to make some business calculations. The issue that comes is that I need to keep records of everything.
First I found some visual basic scripts to read/write .mdb files, but that was too complicated for me since I have never worked with vbs.
So, I decided to use javascript to read/write .csv file
This is the function I found for reading:
function displayClassList() {
var path="log.csv"
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
document.getElementById("searchResults").innerHTML="";
while(!iStream.AtEndOfStream) {
var line=iStream.ReadLine();
document.getElementById("searchResults").innerHTML += line + "<br/>";
}
iStream.Close();
}
It works good.
The problem I have is when it comes to writing. I can not append text to a new line in the document. This is the script I got:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("./ClassList.csv", true);
s.WriteLine("helloworld");
s.Close();
}
The problem with this script is that it replaces all the existing text with "helloworld". What I want is to write "helloworld" in new line. Any solution for that?
Also, is there any way to edit a specific line, like replacing all text in line x?
Here are the scripts for download so that you can test them : http://ge.tt/7u5bDAV2/v/0
If you want to append to the file without overwriting the existing contents, you can use the OpenTextFile method - note that the CreateTextFile method you're using truncates the existing contents.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("./ClassList.csv", 8);
s.WriteLine("helloworld");
s.Close();
There is no easy way of modifying one line of a text file, unless the modifications you're making leave the line the same length, since otherwise if your changes are shorter you will leave part of the old line unchanged, while if your changes are longer you would overwrite the next line.
More importantly, the FileSystemObject does not support seeking, which you would need in order to jump to a specific line.
If you want to modify one line of the file, your best bet is to:
Open the existing file for reading, and also create a new file for writing
Read the existing file line by line, writing the content you want to keep to the new file
Write your modified line(s) to the new file where needed
Close both files, and rename the new file to replace the old one
Having said that, maybe it would be easier for you if your data file was an HTML or XML document rather than a CSV, since you could then use DOM manipulation functions to read and write it.
Generally you use "\n" in your string to create new lines. It represents the newline character in a JS string.
Here's how "lines" work in text files. It's just a long sequence of characters, and one of the possible characters is the newline character. Whatever program renders the file when you view it just knows to show text after a newline character below any text that was before it. You could split the string you read by the newline character and get an Array representing each line and work with it that way. Then to write you'd join that Array by the newline character and write the resulting string.
Note that some programs require "\r\n" to represent a proper newline and won't render new lines for just a "\n"...so try "\r\n" as the newline if you're having trouble getting newlines to work for the program you use to view the text files.
EDIT: Since you don't seem to believe me I'll just prove it to you with code. I did it with an .hta file, but the concept is the same.
Made a text file "myText.txt" and an .hta file with the code in it. The text file held the contents:
This is line 1
Line 2
the third line
line 4 and stuff
fifth line
Then in my code I made these two functions for easily reading and writing:
function getFile(fname)
{
var opener = new ActiveXObject("Scripting.FileSystemObject");
var pointer = opener.OpenTextFile(fname, 1, true);
var cont = pointer.ReadAll();
pointer.Close();
return cont;
}
function setFile(fname, content)
{
var opener = new ActiveXObject("Scripting.FileSystemObject");
var pointer = opener.OpenTextFile(fname, 2, true);
pointer.WriteLine(content);
pointer.Close();
}
For the programs I was using it uses "\r\n" for the newline. So that's what the example will use. I simply utilize splitting and joining on the string of content to edit whatever line of it I choose:
var content = getFile('myFile.txt'); // read it
var lineArr = content.split('\r\n'); // now we have an array of the file's lines
lineArr[2] = 'NEW LINE CONTENT!'; // editing third line (indexed from 0)
var newContent = lineArr.join('\r\n'); // make it text again with newlines
setFile("myFile.txt", newContent); // write it
Now the text file looks like this:
This is line 1
Line 2
NEW LINE CONTENT!
line 4 and stuff
fifth line
Bam. Editing individual lines in a text format file by understanding how newlines work in text.

Categories