Home > Back-end >  How to delete line in multiline string?
How to delete line in multiline string?

Time:06-29

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';
`

CodePudding user response:

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

  • Related