1

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:

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

 

String2 sample:

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 -

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.

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 Answer 1

5

1 - split into separated lines

2 - trim strings

3 - remove empty lines

4 - join it with \n separator.

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')
}
Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately the tool I use support only till ECMAScript3 ,
Then you can easily find polyfills for all methods not supported in your env. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.