1

Hi I have seen many examples for splitting the lines but how can I split lines in txt file if some lines contain \n in their string.

Suppose I have a file with following lines:

"Test \n Line1"
"Test Line 2"

How can I split these two lines as :

ResultArray = ['Test \n Line1', 'Test Line 2']
2
  • Does the original text file contain the quotes? And can the text file have text like this: "string 1" "string 2" or will there always be a \n between the lines? (As well as sometimes within a specific string.) Commented Nov 27, 2017 at 3:42
  • No the string contains \n. It does not contain any quotes. And the strings will be in the next line always. Commented Nov 27, 2017 at 3:45

1 Answer 1

2

You can also try this one,

In your text file just put your strings each in newline without that quotes. After that, your text file should be look something like this,

Test \n Line1
Test Line 2

And where you are reading your text file write

var ResultArray;
fs.readFile('test', 'utf8', function(err, contents) {
    ResultArray = contents.split("\n");
});

Now your resultArray will look like

ResultArray =  ['Test \\n Line1', 'Test Line 2' ];

Don't worry that your resultArray contains items with double \\n. When you try to get some value from your array it will have only one \ like when you do console.log(resultArray[0]) your output will be like

Test \n Line1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.