简体   繁体   English

如何修剪在 Javascript 中具有多行的字符串

[英]How can I trim a string which has multiple lines in Javascript

I have a string with multiple lines which has a single line break between each lines.我有一个多行的字符串,每行之间有一个换行符。 For that I first trim the extra line breaks and then split the string.为此,我首先修剪额外的换行符,然后拆分字符串。 The code used is -使用的代码是 -

function trimString(a){
    var i = a.length;
    var x;
    for (var j = 0; j < i; j++) {
        x = a[j].replace(/^\s*\n/gm,"");
        a[j] = x;
    }
}

function splitLogs(a,s1,s2,s3,s4,s5){
    var i = a.length;
    var x =[];
    for (var j = 0; j < i; j++) {
        x = a[j].split("\n");
        s1.push(x[0]);
        s2.push(x[1]);
        s3.push(x[2]);
        s4.push(x[3]);
        s5.push(x[4]);
        
    }
}

And the above code works fine .上面的代码工作正常。

But the issue is when I have a null/blank value in the multi-line string.但问题是当我在多行字符串中有一个空/空值时。 Whenever a null value is present in a line the string is separated by two line breaks每当一行中存在空值时,字符串就由两个换行符分隔

String1 sample:字符串 1 示例:

line1:Processor
    
line2:  
line3:xyz
    
line4:10
    
line5:user
    
line6:zzz

 

String2 sample: String2 示例:

line1:xy
    
line2:xz
    
line3:qw
    
line4:10
    
line5:df

line6:gg

For the above case If I use the trimString() function the new string obtained is -对于上述情况,如果我使用 trimString() 函数,则获得的新字符串是 -

line1:Processor
line3:xyz
line4:10 
line5:user
line6:zzz

which does not serve my purpose of retaining the null value for line2 and results in mixing up line3 values to line2 array values.这不符合我为 line2 保留 null 值的目的,并导致将 line3 值混合到 line2 数组值。

Is there any way in which I can split the string and push it to respective variables which I have to dump to a database.有什么方法可以拆分字符串并将其推送到我必须转储到数据库的各个变量。

1 - split into separated lines 1 - 分成单独的行

2 - trim strings 2 - 修剪字符串

3 - remove empty lines 3 - 删除空行

4 - join it with \\n separator. 4 - 用\\n分隔符加入它。

const resultString = targetString
  .split('\n')
  .map(line => line.trim())
  .filter(line => Boolean(line))
  .join('\n')

Your function would look like this:您的函数如下所示:

function trimString(a){
  return a.split('\n')
          .map(line => line.trim())
          .filter(line => Boolean(line))
          .join('\n')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM