Javascript Editing Text file - Remove all empty lines but one
I just started learning Javascript and I am trying to implement a project that came into my mind. The project is a simple text editor that takes a text as an input does some corrections and posts an output with the fixed text.
The input text is imported as an array. Each line of the text is an object property. The inputText is for displaying the default text in the browser inside a div, and the outputText is the one I use for the editing.
inputText = loadStrings("v.txt");
outputText = inputText;
Now the input text has some sentences. The problem is that there are a lot of empty lines in between.
firstLine
secondLine
thirdLine
What I want to achieve, is to remove all empty lines, but one, so the output text looks like:
firstLine
secondLine
thirdLine
I am searching for a solution for almost 3 days now. I have managed to remove ALL empty lines, but that's not what i want. I want to remove empty lines if they are more than one, but don't make any change if there is only one empty line.
This piece of code is one of many i have tried. This will remove ALL empty lines:
(source: Remove empty elements from an array in Javascript )
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'n')});
Here is the codepen with all HTML, CSS and the JS code I am using.
https://codepen.io/theokondak/pen/KrNNVz
javascript arrays
|
show 6 more comments
I just started learning Javascript and I am trying to implement a project that came into my mind. The project is a simple text editor that takes a text as an input does some corrections and posts an output with the fixed text.
The input text is imported as an array. Each line of the text is an object property. The inputText is for displaying the default text in the browser inside a div, and the outputText is the one I use for the editing.
inputText = loadStrings("v.txt");
outputText = inputText;
Now the input text has some sentences. The problem is that there are a lot of empty lines in between.
firstLine
secondLine
thirdLine
What I want to achieve, is to remove all empty lines, but one, so the output text looks like:
firstLine
secondLine
thirdLine
I am searching for a solution for almost 3 days now. I have managed to remove ALL empty lines, but that's not what i want. I want to remove empty lines if they are more than one, but don't make any change if there is only one empty line.
This piece of code is one of many i have tried. This will remove ALL empty lines:
(source: Remove empty elements from an array in Javascript )
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'n')});
Here is the codepen with all HTML, CSS and the JS code I am using.
https://codepen.io/theokondak/pen/KrNNVz
javascript arrays
1
To clarify, isinputText
an array, or a string?
– Amadan
Nov 12 '18 at 12:26
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
It does not help at all, sinceloadStrings
is undefined, so there is no indication in code that I can see as to whatinputText
is..filter
works only on arrays, not on any other kinds of object, nor on strings.
– Amadan
Nov 12 '18 at 12:46
|
show 6 more comments
I just started learning Javascript and I am trying to implement a project that came into my mind. The project is a simple text editor that takes a text as an input does some corrections and posts an output with the fixed text.
The input text is imported as an array. Each line of the text is an object property. The inputText is for displaying the default text in the browser inside a div, and the outputText is the one I use for the editing.
inputText = loadStrings("v.txt");
outputText = inputText;
Now the input text has some sentences. The problem is that there are a lot of empty lines in between.
firstLine
secondLine
thirdLine
What I want to achieve, is to remove all empty lines, but one, so the output text looks like:
firstLine
secondLine
thirdLine
I am searching for a solution for almost 3 days now. I have managed to remove ALL empty lines, but that's not what i want. I want to remove empty lines if they are more than one, but don't make any change if there is only one empty line.
This piece of code is one of many i have tried. This will remove ALL empty lines:
(source: Remove empty elements from an array in Javascript )
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'n')});
Here is the codepen with all HTML, CSS and the JS code I am using.
https://codepen.io/theokondak/pen/KrNNVz
javascript arrays
I just started learning Javascript and I am trying to implement a project that came into my mind. The project is a simple text editor that takes a text as an input does some corrections and posts an output with the fixed text.
The input text is imported as an array. Each line of the text is an object property. The inputText is for displaying the default text in the browser inside a div, and the outputText is the one I use for the editing.
inputText = loadStrings("v.txt");
outputText = inputText;
Now the input text has some sentences. The problem is that there are a lot of empty lines in between.
firstLine
secondLine
thirdLine
What I want to achieve, is to remove all empty lines, but one, so the output text looks like:
firstLine
secondLine
thirdLine
I am searching for a solution for almost 3 days now. I have managed to remove ALL empty lines, but that's not what i want. I want to remove empty lines if they are more than one, but don't make any change if there is only one empty line.
This piece of code is one of many i have tried. This will remove ALL empty lines:
(source: Remove empty elements from an array in Javascript )
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'n')});
Here is the codepen with all HTML, CSS and the JS code I am using.
https://codepen.io/theokondak/pen/KrNNVz
javascript arrays
javascript arrays
edited Nov 14 '18 at 2:02
Mike 'Pomax' Kamermans
27.9k75797
27.9k75797
asked Nov 12 '18 at 12:23
TheoKondakTheoKondak
22
22
1
To clarify, isinputText
an array, or a string?
– Amadan
Nov 12 '18 at 12:26
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
It does not help at all, sinceloadStrings
is undefined, so there is no indication in code that I can see as to whatinputText
is..filter
works only on arrays, not on any other kinds of object, nor on strings.
– Amadan
Nov 12 '18 at 12:46
|
show 6 more comments
1
To clarify, isinputText
an array, or a string?
– Amadan
Nov 12 '18 at 12:26
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
It does not help at all, sinceloadStrings
is undefined, so there is no indication in code that I can see as to whatinputText
is..filter
works only on arrays, not on any other kinds of object, nor on strings.
– Amadan
Nov 12 '18 at 12:46
1
1
To clarify, is
inputText
an array, or a string?– Amadan
Nov 12 '18 at 12:26
To clarify, is
inputText
an array, or a string?– Amadan
Nov 12 '18 at 12:26
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
It does not help at all, since
loadStrings
is undefined, so there is no indication in code that I can see as to what inputText
is. .filter
works only on arrays, not on any other kinds of object, nor on strings.– Amadan
Nov 12 '18 at 12:46
It does not help at all, since
loadStrings
is undefined, so there is no indication in code that I can see as to what inputText
is. .filter
works only on arrays, not on any other kinds of object, nor on strings.– Amadan
Nov 12 '18 at 12:46
|
show 6 more comments
5 Answers
5
active
oldest
votes
Try:
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'nn')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[rn]+/g, 'nn');
replacing with two new lines is the simplest way. you will get what you want.
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
|
show 1 more comment
Try this regex:
e.replace(/([rn]){2,}/g, 'nn')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLinennnnsecodLinennnnnnnthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([rn]){2,}/g, 'nn'));
/*
firstLine
secodLine
thirdLine
*/
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
add a comment |
I don't know if loadStrings
leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:r?n){3,}/g, 'nn').
split(/n/).map(line => line + "n");
But you can also do it just with filter
- you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[rn]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
add a comment |
The other answers work with a single string, but you're using the loadStrings()
function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = ;
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
add a comment |
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = 'n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([rn]){1,}/g, 'nn')); // exports the text as it should
return arrayToString.replace(/([rn]){1,}/g, 'nn');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262150%2fjavascript-editing-text-file-remove-all-empty-lines-but-one%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try:
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'nn')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[rn]+/g, 'nn');
replacing with two new lines is the simplest way. you will get what you want.
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
|
show 1 more comment
Try:
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'nn')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[rn]+/g, 'nn');
replacing with two new lines is the simplest way. you will get what you want.
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
|
show 1 more comment
Try:
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'nn')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[rn]+/g, 'nn');
replacing with two new lines is the simplest way. you will get what you want.
Try:
outputText = outputText.filter(function(e){
return e.replace(/[rn]+/g, 'nn')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[rn]+/g, 'nn');
replacing with two new lines is the simplest way. you will get what you want.
edited Nov 12 '18 at 12:55
answered Nov 12 '18 at 12:44
SindhoorSindhoor
285112
285112
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
|
show 1 more comment
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
thats what he want. see his question.
– Sindhoor
Nov 12 '18 at 12:48
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
I have tried this already. whatever i put in the second part of the regular expression field it doesn't make a difference. I have tried replacing n with nn , to leave just some empty quotes or even tried to put some string value to see if it even makes a difference. It does not.
– TheoKondak
Nov 12 '18 at 12:49
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
it will make difference. i tried and posted the answer.
– Sindhoor
Nov 12 '18 at 12:50
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
updated answer. use without using filter function. must work.
– Sindhoor
Nov 12 '18 at 12:55
@Sindhoor I've tried the updated single line code you suggested, but i get an error:
index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
@Sindhoor I've tried the updated single line code you suggested, but i get an error:
index.js:80 Uncaught (in promise) TypeError: outputText.replace is not a function at removeEmptyLines
– TheoKondak
Nov 12 '18 at 13:37
|
show 1 more comment
Try this regex:
e.replace(/([rn]){2,}/g, 'nn')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLinennnnsecodLinennnnnnnthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([rn]){2,}/g, 'nn'));
/*
firstLine
secodLine
thirdLine
*/
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
add a comment |
Try this regex:
e.replace(/([rn]){2,}/g, 'nn')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLinennnnsecodLinennnnnnnthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([rn]){2,}/g, 'nn'));
/*
firstLine
secodLine
thirdLine
*/
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
add a comment |
Try this regex:
e.replace(/([rn]){2,}/g, 'nn')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLinennnnsecodLinennnnnnnthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([rn]){2,}/g, 'nn'));
/*
firstLine
secodLine
thirdLine
*/
Try this regex:
e.replace(/([rn]){2,}/g, 'nn')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLinennnnsecodLinennnnnnnthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([rn]){2,}/g, 'nn'));
/*
firstLine
secodLine
thirdLine
*/
answered Nov 12 '18 at 13:37
Hélio Márcio FilhoHélio Márcio Filho
19129
19129
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
add a comment |
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
I have tried just your code and it works indeed. In my code though, i have to work with either an object or an array (really i am confused on what it is right now). Maybe your solution would work, if i load the file as one string, and not an object or an array?
– TheoKondak
Nov 12 '18 at 13:46
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
You can use Array.reduce() to transform your array of lines in a single string containing all the lines before to apply this solution. Something like: arrayOfLines.reduce((final, line) => { return final += line}, "").
– Hélio Márcio Filho
Nov 12 '18 at 14:29
add a comment |
I don't know if loadStrings
leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:r?n){3,}/g, 'nn').
split(/n/).map(line => line + "n");
But you can also do it just with filter
- you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[rn]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
add a comment |
I don't know if loadStrings
leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:r?n){3,}/g, 'nn').
split(/n/).map(line => line + "n");
But you can also do it just with filter
- you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[rn]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
add a comment |
I don't know if loadStrings
leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:r?n){3,}/g, 'nn').
split(/n/).map(line => line + "n");
But you can also do it just with filter
- you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[rn]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
I don't know if loadStrings
leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:r?n){3,}/g, 'nn').
split(/n/).map(line => line + "n");
But you can also do it just with filter
- you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[rn]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
answered Nov 12 '18 at 16:25
AmadanAmadan
130k13142193
130k13142193
add a comment |
add a comment |
The other answers work with a single string, but you're using the loadStrings()
function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = ;
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
add a comment |
The other answers work with a single string, but you're using the loadStrings()
function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = ;
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
add a comment |
The other answers work with a single string, but you're using the loadStrings()
function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = ;
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
The other answers work with a single string, but you're using the loadStrings()
function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = ;
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
answered Nov 12 '18 at 18:17
Kevin WorkmanKevin Workman
33.8k54069
33.8k54069
add a comment |
add a comment |
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = 'n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([rn]){1,}/g, 'nn')); // exports the text as it should
return arrayToString.replace(/([rn]){1,}/g, 'nn');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.
add a comment |
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = 'n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([rn]){1,}/g, 'nn')); // exports the text as it should
return arrayToString.replace(/([rn]){1,}/g, 'nn');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.
add a comment |
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = 'n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([rn]){1,}/g, 'nn')); // exports the text as it should
return arrayToString.replace(/([rn]){1,}/g, 'nn');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = 'n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([rn]){1,}/g, 'nn')); // exports the text as it should
return arrayToString.replace(/([rn]){1,}/g, 'nn');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.
answered Nov 13 '18 at 15:58
TheoKondakTheoKondak
22
22
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262150%2fjavascript-editing-text-file-remove-all-empty-lines-but-one%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
To clarify, is
inputText
an array, or a string?– Amadan
Nov 12 '18 at 12:26
The inputText is an object.
– TheoKondak
Nov 12 '18 at 12:36
Without more information as to the structure of said object, it will not be possible to give you an answer.
– Amadan
Nov 12 '18 at 12:37
@Amadan I Have updated the original post with a codepen including all my code. It's on the last line of the original post.
– TheoKondak
Nov 12 '18 at 12:42
It does not help at all, since
loadStrings
is undefined, so there is no indication in code that I can see as to whatinputText
is..filter
works only on arrays, not on any other kinds of object, nor on strings.– Amadan
Nov 12 '18 at 12:46