0

I have a multiline stock. How can I remove a specific line?

const str = `
  import 'C:\Users\Desktop\sanitize.js';
  val = ln + '\t';
  val += lc + '\t';
  val += f + '\t'; 
  val += id + '\t'; // id source
  val += sc + '\t\n';
`;

In this case, I need to delete lines where Import or reguired occurs, while maintaining line breaks.

My approach doesn't work, because there can be a line break inside the lines, and I'm trying to split the line by line breaks in order to achieve the result.

function sanitizeSandbox(code) {
  let disinfectedSandbox = '';

  if (typeof code === 'string' && code.length > 0) {
    const sandboxSplit = code.split('\n');
    
    for (const str of sandboxSplit) {
      if (!str.includes('import') && !str.includes('required')) {
        disinfectedSandbox += `${str}\n`;
      }
    }
  }

  return disinfectedSandbox;
}

Expected value:

`
 val = ln + '\t';
 val += lc + '\t';
 val += f + '\t'; 
 val += id + '\t'; // id source
 val += sc + '\t\n';
`

The value I get with my approach:

`
 val = ln + '\t';
 val += lc + '\t';
 val += f + '\t';
 val += id + '\t'; // id source
 val += sc + '\t
 \n';
`
Vladislav
  • 125
  • 6

1 Answers1

1

You can use this regex (derived from this answer):

(?:[^\n']|'[^']*')+

to match lines in your string (while ignoring newlines within ''), then filter based on whether or not the line contains import or required:

const str = `
  import 'C:\Users\Desktop\sanitize.js';
  val = ln + '\t';
  val += lc + '\t';
  val += f + '\t'; 
  val += id + '\t'; // id source
  val += sc + '\t\n';
`;

result = str.match(/(?:[^\n']|'[^']*')+/g)
  .filter(l => !l.match(/\b(import|require)\b/))
  .join('\n')
  
console.log(result)
console.log(JSON.stringify(result))
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Is it possible to somehow ignore special characters when working with strings? Now, when executing, instead of \t, a space is put, and instead of \n, a line break. Is it possible to leave special characters in their places and not execute them? – Vladislav Jun 29 '22 at 05:30
  • @Vladislav I'm not sure exactly what you mean. This code is independent of what is in the lines, it only cares about the newlines at the end. – Nick Jun 29 '22 at 05:32
  • there is a newline on the fifth line which I would like to ignore – Vladislav Jun 29 '22 at 05:37
  • please look again at the value that I expect – Vladislav Jun 29 '22 at 05:38
  • @Vladislav take a look at the output of my code, the newline is present in the output string. It just shows up as a newline when logged to the console. Take a look at my edit, I'm outputting the JSON encoded string as well and you can see the newline present as expected. – Nick Jun 29 '22 at 06:07
  • thanks a lot i was able to figure it out – Vladislav Jun 29 '22 at 06:37
  • @Vladislav OK. great, I'm glad I could help – Nick Jun 29 '22 at 06:38