JavaScript: how to remove line that contain specific string
How can I remove a complete line if it开发者_C百科 contains a specific string like the following?
#RemoveMe
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.
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.
精彩评论