matt
matt

Reputation: 321

How to replace all newlines after reading a file

How can I replace a newline in a string with a ','? I have a string that is read from a file:

const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);

It takes a string from a file:

a,b,c,d,e,f
,,,,,
g,h,i,j,k,l

I'm able to detect the newline with this:

if (char === '\n')

But replacing \n like this doesn't work

str = csvString.replace('/\n/g');

I want to get the string to look like this:

a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,

Upvotes: 2

Views: 231

Answers (5)

Nader-a
Nader-a

Reputation: 123

I believe in some systems newline is \r\n or just \r, so give /\r?\n|\r/ a shot

Upvotes: 0

Manish Khedekar
Manish Khedekar

Reputation: 402

You may try out like,

// Let us have some sentences havin linebreaks as \n.

let statements = " Programming is so cool. \n We love to code. \n We can built what we want. \n :)";

// We will console it and see that they are working fine.
console.log(statements);

// We may replace the string via various methods which are as follows,

// FIRST IS USING SPLIT AND JOIN
let statementsWithComma1 = statements.split("\n").join(",");

// RESULT
console.log("RESULT1 : ", statementsWithComma1);

// SECOND IS USING REGEX
let statementsWithComma2 = statements.replace(/\n/gi, ',');

// RESULT
console.log("RESULT2 : ", statementsWithComma2);

// THIRS IS USING FOR LOOP
let statementsWithComma3 = "";

for(let i=0; i < statements.length; i++){
  if(statements[i] === "\n")
    statementsWithComma3 += ','
  else
    statementsWithComma3 += statements[i]
}

// RESULT
console.log("RESULT3 : ", statementsWithComma3);

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

Try replacing the pattern $ with ,, comma:

var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);

Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.

Upvotes: 1

Dananjaya Ariyasena
Dananjaya Ariyasena

Reputation: 606

let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;

let edited = text.replace(/\s+/g, '');

console.log( edited )

You can try this solution also. \s means white spaces.

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can add , at end of each line like this

  • $ - Matches end of line

let str = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`

let op = str.replace(/$/mg, "$&"+ ',')

console.log(op)

Upvotes: 1

Related Questions