Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 681
Abdulrahman Ishaq Avatar asked May 28 '10 16:05

Abdulrahman Ishaq


People also ask

How do I remove a specific part of a string in Javascript?

To remove all occurrences of a substring from a string, call the replaceAll() method on the string, passing it the substring as the first parameter and an empty string as the second. The replaceAll method will return a new string, where all occurrences of the substring are removed.

How do I delete a specific text in a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.

How do you remove line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do you remove all occurrences of a character from a string in Javascript?

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.


1 Answers

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.

like image 154
Christian C. Salvadó Avatar answered Sep 20 '22 12:09

Christian C. Salvadó