读取文件后如何替换所有换行符

时间:2019-05-29 05:07:37

标签: javascript

如何用','替换字符串中的换行符?我有一个从文件读取的字符串:

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

它从文件中获取一个字符串:

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

我可以通过以下方式检测换行符:

if (char === '\n')

但是像这样替换\ n不起作用

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

我想让字符串看起来像这样:

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

5 个答案:

答案 0 :(得分:1)

尝试将模式$替换为,,逗号:

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

由于您打算保留换行符/回车符,因此我们可以利用$来代表每行的结尾。

答案 1 :(得分:1)

您可以像这样在每行的末尾添加,

  • $-匹配行尾

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

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

console.log(op)

答案 2 :(得分:0)

我相信在某些系统中,换行符是\r\n或仅仅是\r,所以请给/\r?\n|\r/试一下

答案 3 :(得分:0)

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

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

console.log( edited )

您也可以尝试此解决方案。 \s表示空格。

答案 4 :(得分:0)

您可以尝试一下,

// 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);