Abdulrahman Ishaq
Abdulrahman Ishaq

Reputation: 201

JavaScript: how to remove line that contain specific string

How can I remove a complete line if it contains a specific string like the following?

#RemoveMe

Upvotes: 20

Views: 14218

Answers (2)

Archit Agarwal
Archit Agarwal

Reputation: 141

As suggested by @CMS , it simply replaces the line with "", still there is an extra line.

For String:

var str = 'line1\n'+
'line2\n'+
'#RemoveMe line3\n'+
'line4'; 

If you want the output like this :

line1
line2
line4

instead of

line1
line2

line4

Try this :

str.split('\n').filter(function(line){ 
    return line.indexOf( "#RemoveMe" ) == -1;
  }).join('\n')

All the lines containing the string '#RemoveMe' are simply filtered out, also multiple keywords can be used during filtering.

Upvotes: 8

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827356

If you have a multi-line string, you could use a RegExp with the m flag:

var str = 'line1\n'+
'line2\n'+
'#RemoveMe line3\n'+
'line4';

str.replace(/^.*#RemoveMe.*$/mg, "");

The m flag will treat the ^ and $ meta characters as the beginning and end of each line, not the beginning or end of the whole string.

Upvotes: 45

Related Questions